0

我有一个组件应用程序列表,它在所有组件中都被调用。我还有另外两个组件 app-cmp1 和 app-cmp2。

在我们调用的每个组件 app-cmp1 和 app-cmp2 中,app-list 和 app-list 从 api.app-list 加载数据默认是隐藏的。当用户单击链接时,会打开。

现在的问题是每次打开 App-list 时,它都会从 api 加载数据。如果数据加载一次,我们有没有办法阻止 app-list 调用 api。

4

2 回答 2

0

您可以将数据缓存在被调用的服务中,并在调用时检查它是否可用:

在被调用的服务内部:

...
data : any ;

fetchData(forceReload : boolean) : Observable<any>{
   if (!forceReload && this.data){
       return of(data) ;
   }
return this.http.get(url)
       .pipe(
        tap(resp => this.data = resp)
        ) ;
}
...
于 2020-02-04T10:20:16.813 回答
0

You can build an observable-based cache layer:

export class CachedDataService {

    private cache: { [index: string]: { reloader: Subject<void>, data: Observable<any> } } = {};

    constructor(private http: HttpClient){}

    public get<T>(url: string, reloadIfExists = false): Observable<T> {
        if (this.cache[url] === undefined) {
            const reloader = new BehaviorSubject<void>(null);
            this.cache[url] = {
                reloader: reloader,
                data: reloader.pipe(
                    switchMapTo(this.http.get<T>(url))
                )
            };
        } else if (reloadIfExists) {
            this.cache[url].reloader.next();
        }
        return this.cache[url].data;
    }

}

this way, you can fetch data as you want, and you have full control on the reloader, which will propagate the reloaded data to all the subscribers.

于 2020-02-04T10:27:58.063 回答