我想要实现的是将数据保存到缓存中。
我的解决方案:
public coursesCache;
public getCourses(): Observable<any> {
const courses$ = this.coursesCache
? of(this.coursesCache)
: this.courseService.getCourses().pipe(
tap(courses=> this.coursesCache = courses)
);
return courses$;
}
使用这种方法实施有什么问题吗? 有更好的方法来实现吗?
只需使用 rxjs
share
运算符即可!
cache = this.courseService.getCourses().pipe(
share(), // <- changed here!
);
public getCourses(): Observable<any> {
return cache;
}