Angular RxJS缓存Http结果
我正在将Angular v1.4应用程序迁移到v5(希望在新的一年中是v6) 该应用程序有许多组件,例如标题、选项卡、网格、图像、身份验证等 每个组件生成特定的Angular RxJS缓存Http结果,angular,caching,rxjs,Angular,Caching,Rxjs,我正在将Angular v1.4应用程序迁移到v5(希望在新的一年中是v6) 该应用程序有许多组件,例如标题、选项卡、网格、图像、身份验证等 每个组件生成特定的http.get以获取系统和用户首选项,并缓存结果以避免应用程序生成多个相同的http.get 看起来RxJS是一个功能强大的库,可以使用。似乎有很多例子、方法和视图可以用RxJS实现这种缓存 想分享我在v5应用程序中所做的工作并获得反馈。在DevTools中检查应用程序时,似乎只执行了1个http.get,因此它似乎可以工作 syste
http.get
以获取系统和用户首选项,并缓存结果以避免应用程序生成多个相同的http.get
看起来RxJS是一个功能强大的库,可以使用。似乎有很多例子、方法和视图可以用RxJS实现这种缓存
想分享我在v5应用程序中所做的工作并获得反馈。在DevTools中检查应用程序时,似乎只执行了1个http.get,因此它似乎可以工作
systemPreferences.service.ts:
const CACHE_SIZE = 1;
export class SystemPreferences {
private $cache: Observable<Object>
private requestConfig() {
return this.http.get("www.someurl.com").pipe(
map(response => response.value)
);
}
public getPreferences() {
if (!this.cache$) {
this.cache$ = this.requestConfig().pipe(
shareReplay(CACHE_SIZE)
);
}
return this.cache$;
}
}
routingGuard canActivate、tabs等的组件代码相同那么你的问题是什么?我的问题是,我不知道这是否是执行缓存的正确“rxjs”方法?是的,基本上是这样。请注意,您应该在
shareReplay
之后添加take(1)
,因为否则无法完成可观察内容。可能会重复
ngOnInit() {
this.systemPreferences.getPreferences()
.subscribe(
(result: any) => {
this.headerTitle = result.title || '';
},
(err) => {
console.log('there has been an error');
},
() => // Some completion code
);
}