点击minister
路由器链接时,我有一个非常简单的API调用。当部长页面打开时,它将显示一些数据。但是,无论何时从首页或任何其他页面返回该页面时,API都会再次加载。
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;
});
}
}
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')
}
}
答案 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)
“缓存”,并且每次都返回相同的值。