我使用 shareReplay
只调用一次(像缓存一样)网络服务来检索一些信息:
在我的服务中:
getProfile(): Observable<Customer> {
return this.callWS().pipe(shareReplay(1));
}
在多个组件中:
this.myService.getProfile().subscribe(customer => {
console.log('customer informations has been retrieved from WS :', customer);
});
现在我想添加一个方法来强制刷新信息(只绕过 shareReplay 一次)。我尝试将我的 observable 存储在一个变量中,并在重新初始化它之前将其设置为 null,但它似乎破坏了组件订阅..
有什么帮助吗?
谢谢
最佳答案
我知道这个线程是旧的,但我想我知道另一个答案是什么意思,即在前面加上一个“重置”主题以推送新值。检查这个例子:
private _refreshProfile$ = new BehaviorSubject<void>(undefined);
public profile$: Observable<Customer> = _refreshProfile$
.pipe(
switchMapTo(this.callWS()),
shareReplay(1),
);
public refreshProfile() {
this._refreshProfile$.next();
}
在上面的代码片段中,所有 profile$
新订阅者都将收到最新发出的值(在调用 callWS()
一次后)。如果您希望“刷新”正在共享的客户,您可以调用“refreshProfile()”。这将通过 switchMapTo
发出一个新值,重新分配重播值并通知任何 profile$
打开的订阅者。
祝你好运
关于typescript - RxjS shareReplay : how to reset its value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348406/