如何解决订阅Observable-Angular 10之前将API数据存储在主题中
我正在尝试使用下一种方法将API返回的数据存储在行为主体内,我希望在订阅可观察对象之前进行此操作。
假设我有一项服务,该服务具有从API检索一些数据的功能:
getData(): Observable<Data> {
return this.http.get(APIURL);
}
现在,在订阅getData()之前,我想将API返回的内容保存在主题中。我设法用tap()运算符实现了这一点,但是通过阅读文档,tap应该用于副作用,在这种情况下,它看起来不像一个。 所以我所做的就是这样:
getData(): Observable<Data> {
return this.http.get(APIURL)
.pipe(tap(data => this.subject.next(data));
}
我正在这样做,所以我可以拥有某种缓存,这样我就不必再次调用API并在数据更新时对其进行一些处理。例如,假设我通过更新查询向该数据添加了一个元素,现在我可以更新存储在主题中的先前数据,因此所有内容都是最新的。只有刷新页面,我才能再次调用API。
我不清楚是使用tap运算符,可以像这样使用它,还是我想做的更好的选择?
解决方法
如果我理解正确,您可以检查一下主题中是否有数据
subject = new BehaviorSubject<any>(null);
getData(): Observable<Data> {
if (subject.getValue()) {
return of(subject.getValue());
}
return this.http.get(APIURL)
.pipe(tap(data => this.subject.next(data));
}
,
这里是CodeSandbox,它显示了在不使用状态管理库的情况下管理高速缓存请求流的一种方法。
该演示的实质如下
interface IArticle {
title: string;
content: string;
}
@Injectable({ providedIn: "root" })
export class HttpDemoCache {
// You need a variable where to store the data
cachedArticleResponse$: BehaviorSubject<IArticle[]> = new BehaviorSubject([]);
...
loadArticles(someQuery) {
// You need a method that fetches the data from the BE
this.httpClient.get(...).subscribe((x) => {
this.cachedArticleResponse$.next(x);
});
}
updateArticles(newArticle: IArticle) {
// You need a update method to send the new enttity to the back-end + update your cached version
this.http.post(....,{newArticle}).pipe(
switchMap(response =>
this.cachedArticleResponse$
.pipe(
take(1),tap(cachedArtilces => this.cachedArticleResponse$
.next([...cachedArticles,newArticle]))
)
)
).subscribe()
});
}
}
使用此解决方案,您正在创建自己的状态管理解决方案,其职责是照顾所有cahce / fetch / upload / delete逻辑。
此解决方案的好处是,与直接在组件中获取数据相比,您可以更好地控制正在发生的事情。
**旁注:请记住,这只是概念的简短示例,而不是详细的解决方案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。