在Angular 7中缓存API结果的解决方法可以通过使用RxJS的shareReplay
操作符来实现。
首先,您需要导入HttpClient
和shareReplay
操作符:
import { HttpClient } from '@angular/common/http';
import { shareReplay } from 'rxjs/operators';
然后,您可以在服务中定义一个公共的方法来获取API数据,并使用shareReplay
操作符来缓存结果:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { shareReplay } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private cachedData$: Observable;
constructor(private http: HttpClient) { }
getData(): Observable {
if (!this.cachedData$) {
this.cachedData$ = this.http.get('https://api.example.com/data').pipe(
shareReplay(1)
);
}
return this.cachedData$;
}
}
在上面的示例中,getData
方法首先检查cachedData$
是否存在。如果不存在,它会发起HTTP请求并使用shareReplay
操作符来缓存结果。如果cachedData$
已经存在,则直接返回已缓存的结果。
然后,您可以在组件中调用getData
方法来获取API数据:
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-my-component',
template: `
`
})
export class MyComponent implements OnInit {
data$;
constructor(private apiService: ApiService) { }
ngOnInit() {
this.data$ = this.apiService.getData();
}
}
在上面的示例中,我们使用async
管道来订阅data$
Observable并在模板中显示API数据。
通过使用shareReplay
操作符,您可以确保只发起一次HTTP请求并在多个订阅之间共享结果。这样可以减少不必要的网络请求,并提高应用程序的性能。