在Angular应用程序中,我进行了以下处理:
OnInit从主题调用(SubjectOne)启动子订阅
当有来自SubjectOne的新数据时,
,如果某些条件得到验证;我重新使用这些数据来发起第二次呼叫,这是来自服务呼叫的http呼叫。
这是我的代码
MyComponent.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)=>{}
}
}
MyService.ts
sendToBackend(thatValue){
let newValue = someFormatingnMethod(thatValue)
return this.httpClient.post(url , newValue );
}
我的目的是如何动态关闭 subscribtionTwo ,这样,每次我从主题获取新数据后,它就不会被调用n次。
注意: mySubject甚至可以在销毁组件之前注意到一些新数据
我尝试使用switchMap
,但似乎无法正常工作
建议?
答案 0 :(得分:2)
我会采用这种方法:
takeUntil
取消销毁filter
仅根据条件继续switchMap
运行第二个可观察的HttpClient
请求,该请求会自动完成,因此我们不需要退订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);
}