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

时间:2018-12-31 06:24:29

标签: javascript angular typescript

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

duplicate api calls

minister.component.ts

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')
    }
}

1 个答案:

答案 0 :(得分:6)

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

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)“缓存”,并且每次都返回相同的值。