我有以下要求。
我有一个带有BehaviorSubject 的Angular 服务。http 请求完成后,将使用该值调用BehaviorSubject.next 方法。该值在单页的生命周期中可能会发生变化。
不同的订阅者会注册到它,并在发生变化时被调用。
问题是,当 http 请求挂起时,BehaviorSubject 已经包含默认值,并且订阅者已经立即获取该值。
我想要的是订阅者必须等到 http 请求完成(延迟)并在 http 请求完成并设置值时获取值。所以我需要的是某种延迟行为主体机制。
我如何使用 rxjs 来实现这个?
另一个要求是,如果我在方法中订阅行为主体,我们希望订阅者获得第一个非默认值并且订阅结束。我们不希望重新执行函数中的本地订阅。
对您的行为主题使用过滤器,这样您的订阅者就不会获得第一个默认发出的值:
mySubject$: BehaviorSubject<any> = new BehaviorSubject<any>(null);
httpResponse$: Observable<any> = this.mySubject$.pipe(
filter(response => response)
map(response => {
const modifyResponse = response;
// modify response
return modifyResponse;
}),
take(1)
);
this.httpResponse$.subscribe(response => console.log(response));
this.myHttpCall().subscribe(response => this.mySubject$.next(response));
Run Code Online (Sandbox Code Playgroud)
如果需要,您当然可以将 httpResponse$ observable 包装在方法中。
| 归档时间: |
|
| 查看次数: |
1857 次 |
| 最近记录: |