代码之家  ›  专栏  ›  技术社区  ›  Oam Psy

RxJS缓存Http结果

  •  2
  • Oam Psy  · 技术社区  · 6 年前

    这个应用程序有很多组件,例如头、标签、网格、图像、身份验证等。

    每种成分都有其特殊性 http.get 获取系统和用户的首选项,并缓存结果,以避免应用程序生成同一http.get的多个。

    想分享我在v5应用程序中所做的事情并获得反馈。在DevTools中检查应用程序时,似乎只执行了1个http.get,因此它似乎工作正常。。

    系统首选项.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$;
        }
    }
    

    标题.component.ts:

    ngOnInit() {
        this.systemPreferences.getPreferences()
            .subscribe(
                (result: any) => {
                    this.headerTitle = result.title || '';
                },
                (err) => {
                    console.log('there has been an error');
                },
                () => // Some completion code
            );
    }
    

    0 回复  |  直到 6 年前