如果您出于性能原因想要缓存 GET 请求的响应,或者即使在离线时也能传递数据,那么正如 Dilshan 所说,您可以使用添加原理图添加 service worker 模块。
在这里full step by step demo 了解如何使用 Angular 创建 PWA。
然后在 ngsw-config.json 文件中,您将 API 请求定位到 dataGroups 数组中:
"dataGroups": [{
"name": "jokes-cache",
"urls": [ "https://icanhazdadjoke.com/" ],
"cacheConfig": {
"strategy": "performance",
"maxSize": 5,
"maxAge": "1d"
}
},
{
"name": "stocks-cache",
"urls": [ "https://api.worldtradingdata.com/api/v1/stock" ],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 10,
"maxAge": "1d",
"timeout": "10s"
}
}]
但是如果你想存储一些数据并在其他组件之间共享,那么你可以使用RxJs ReplaySubject。下面的代码执行GET,然后在本地缓存结果。所以后面的调用不会触发新的请求,而是会返回缓存的数据。
getUsers(reload: boolean = false): Observable<User[]> {
if (!this.cache$ || reload) {
if (!this.cache$) {
this.cache$ = new ReplaySubject<User[]>(1);
}
this.getUsersFromServer()
.pipe(
map(result => result.map(f => new User(f)))
)
.subscribe(
users => this.cachedInvoices$.next(users)
);
}
return this.cache$.asObservable();
}