缓存服务的最佳方法

问题描述 投票:0回答:1

我想要实现的是将数据保存到缓存中。

我的解决方案:

  public coursesCache;
  public getCourses(): Observable<any> {
    const courses$ = this.coursesCache
      ? of(this.coursesCache)
      : this.courseService.getCourses().pipe(
        tap(courses=> this.coursesCache = courses)
      );

    return courses$;
  }

使用这种方法实施有什么问题吗? 有更好的方法来实现吗?

angular rxjs
1个回答
0
投票

只需使用 rxjs

share
运算符即可!

cache = this.courseService.getCourses().pipe(
    share(), // <- changed here!
);

public getCourses(): Observable<any> {
    return cache;
}
© www.soinside.com 2019 - 2024. All rights reserved.