Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular RxJS缓存Http结果_Angular_Caching_Rxjs - Fatal编程技术网

Angular RxJS缓存Http结果

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

我正在将Angular v1.4应用程序迁移到v5(希望在新的一年中是v6)

该应用程序有许多组件,例如标题、选项卡、网格、图像、身份验证等

每个组件生成特定的
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
        );
}