![](/img/trans.png)
[英]RxJS Subscribing varying amount of Observables inside Subscription
[英]RxJS : how to organize subscription betwen nested subscribing calls
在我的 Angular 应用程序中,我进行了以下处理:
从主题调用 (SubjectOne) 启动订阅者的 OnInit
当有来自 SubjectOne 的新数据时,
如果某些条件得到验证; 我重新使用这些数据来启动第二个调用,这是来自服务调用的 http 调用。
这是我的代码
我的组件.ts :
ngOnInit() {
this.getFirstTreatment();
}
getFirstTreatment() {
this.subscriptionOne = this.myService.subjectOne.subscribe((data) => {
this.myValue = data['myValue'];
this.getSecondTreatment(data['myValue'])
})
}
getSecondTreatment(thatValue) {
if(thatValue >= 100){
this.subscriptionTwo = this.myService.sendToBackend(thatValue).subscribe((response)=>{}
}
}
我的服务.ts
sendToBackend(thatValue){
let newValue = someFormatingnMethod(thatValue)
return this.httpClient.post(url , newValue );
}
我的目的是我如何动态关闭subscribtionTwo以便每次从主题获取新数据后它不会被调用 n 次。
注意:即使在销毁组件之前,mySubject 也可以注意到一些新数据
我尝试使用switchMap
,但它似乎无法正常工作
建议?
我会采取这种方法:
takeUntil
在销毁时取消订阅filter
仅根据条件继续switchMap
运行第二个 observableHttpClient
请求,它自己完成,所以我们不需要取消订阅private destroyed$ = new Subject();
ngOnInit() {
getFirstTreatment();
}
ngOnDestroy() {
this.destroyed$.next();
this.destroyed$.complete();
}
getFirstTreatment() {
this.myService.subjectOne.pipe(
takeUntil(this.destroyed$),
tap(data => this.myValue = data['myValue']),
filter(data => data['myValue'] >= 100),
switchMap(data => this.getSecondTreatment(data['myValue']))
).subscribe(data => {
console.log(data); // the output of the second observable
});
}
getSecondTreatment(myValue): Observable<any> {
return this.getSecondTreatment(myValue);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.