单击minister路由器链接时,我有一个非常简单的API调用。当部长页面打开时,它将显示一些数据。但是,无论何时从首页或任何其他页面返回该页面,API都会再次加载。

javascript - 如何停止angular中重复的api调用-LMLPHP

部长组件

import { Component, OnInit } from '@angular/core';
import { ApiReadService } from "../apiReadService.service";

interface mydata{
  allMinisters: Object
}

@Component({
  selector: 'app-ministers',
  templateUrl: './ministers.component.html',
  styleUrls: ['./ministers.component.scss']
})
export class MinistersComponent implements OnInit {

  allData:Object = [];

  constructor(private apiRead: ApiReadService) {

  }
  ngOnInit(){
  this.apiRead.getData().subscribe(data=>{
            this.allData  = data.allMinisters;
    });
  }
}

apiReadSerivce.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/Http';

@Injectable({
  providedIn: 'root'
})

export class ApiReadService {
    constructor(private http: HttpClient) { }

    getData(){
        return this.http.get('http://localhost:8081/allMinisters')
    }
}

最佳答案

最简单的方法-如果您只想一次加载数据,则如下所示:

import { shareReplay } from 'rxjs/operators';

export class ApiReadService {
   constructor(private http: HttpClient) { }

   ministers$ = this.http.get('http://localhost:8081/allMinisters')
                         .pipe(shareReplay(1))

   getData() {
      return this.ministers$;
   }
}

一旦返回结果,它就会被shareReplay(1)“缓存”,并且每次都返回相同的值。

09-25 20:31