Angular 4 路由在每次加载组件时都会调用 ngOnInit,导致重复的 API 调用。
创始人
2024-10-15 19:00:46
0

在Angular 4中,当组件被路由导航到时,ngOnInit()方法会被调用。如果在每次加载组件时都发起API调用,可能会导致重复的API请求。为了解决这个问题,可以使用Angular的生命周期钩子和服务来进行处理。

首先,创建一个服务来处理API调用。在服务中,使用一个属性来存储已经获取的数据,以便在后续的调用中重复使用。这样就可以避免重复的API请求。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {
  private cachedData: any;

  constructor(private http: HttpClient) {}

  getData() {
    if (this.cachedData) {
      // 如果已经有缓存的数据,直接返回
      return Promise.resolve(this.cachedData);
    } else {
      // 否则发起API请求,获取数据并缓存
      return this.http.get('your-api-url').toPromise()
        .then(data => {
          this.cachedData = data;
          return data;
        });
    }
  }
}

然后,在组件中使用该服务来获取数据。在ngOnInit()方法中调用服务的getData()方法,这样就可以确保只有在第一次加载组件时才会发起API请求。

import { Component, OnInit } from '@angular/core';
import { DataService } from 'your-data-service';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
  data: any;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.getData()
      .then(data => this.data = data);
  }
}

通过这种方式,只有在第一次加载组件时才会发起API请求,并且之后的每次加载都会直接使用缓存的数据,避免了重复的API调用。

相关内容

热门资讯

透视解迷!uupoker有透视... 透视解迷!uupoker有透视吗(透视)德普之星透视,教程妙招(有挂教学)-哔哩哔哩1、透视解迷!u...
透视开挂!wepokerplu... 透视开挂!wepokerplus透视脚本免费(透视)德普辅助软件,教程手册(真实有挂)-哔哩哔哩1、...
透视解谜!德普之星辅助器app... 透视解谜!德普之星辅助器app(透视)拱趴大菠萝开挂方法,教程技法(证实有挂)-哔哩哔哩1)拱趴大菠...
透视解迷!pokerrrr2辅... 透视解迷!pokerrrr2辅助(透视)哈糖大菠萝攻略,教程方案(有挂秘诀)-哔哩哔哩1、哈糖大菠萝...
透视解谜!WePoKer辅助器... 透视解谜!WePoKer辅助器(透视)wepoker私人局俱乐部辅助,教程积累(有挂规律)-哔哩哔哩...
透视开挂!sohoo竞技联盟辅... 透视开挂!sohoo竞技联盟辅助器(透视)德州局透视脚本免费版下载手机版,教程妙计(有挂神器)-哔哩...
透视揭幕!aapoker能控制... 透视揭幕!aapoker能控制牌吗(透视)epoker底牌透视,教程资料(确实有挂)-哔哩哔哩1、玩...
透视分享!wepoker有辅助... 您好,wepoker有辅助器吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
透视推荐!wepoker软件辅... 透视推荐!wepoker软件辅助程序(透视)wepoker软件辅助程序,教程烘培(有挂解密)-哔哩哔...
透视科普!hhpoker是正规... 透视科普!hhpoker是正规的吗(透视)hhpoker辅助器视频,教程窍要(详细教程)-哔哩哔哩1...