[英]RxJs : How to close subscription of nested observable.subscribe call
Within my Angular app :在我的 Angular 应用程序中:
i ve this treatment :我有这样的治疗:
mySubjectOne = new Subject();
methodOne(){
this.subscriptionOne = mySubjectOne.subscribe((response) => {
this.methodTwo();
})
}
methodTwo(){
this.subscriptionTwo = return this.httpClient.post(myurl , mydata).subscribe((response) => {
myTreatment(); // MY TREATMENT
})
}
My probleme is whenever " mySubjectOne " is called methodOne calls methodTwo ,我的问题是每当“ mySubjectOne ”被称为methodOne调用methodTwo 时,
and the subscriptionTwo seems to be cloned to be +1 every time :并且 subscriptionTwo 似乎每次都被克隆为 +1 :
for example in the third time of calling : methodOne , it seems that there were 4 subscriptionTwo invoqued比如第三次调用:methodOne,好像调用了4个subscriptionTwo
How may i close the subsrciption subscriptionTwo just after TREATMENT and let it be recreated in each rime我如何在 TREATMENT 之后关闭 subsrciption subscriptionTwo 并让它在每个 rime 中重新创建
Suggestions ?建议?
You can use switchMap to achieve exactly this behavior.您可以使用switchMap来实现这种行为。 Note that there are also other operators such as
exhaustMap
or mergeMap
that may fit your desired behavior even more.请注意,还有其他运算符,例如
exhaustMap
或mergeMap
,它们可能更适合您想要的行为。 Read up on the source provided.阅读提供的来源。
mySubjectOne = new Subject();
methodOne() {
this.subscriptionOne = mySubjectOne.pipe(
switchMap((response) => this.methodTwo()),
)
.subscribe((response) => {
myTreatment();
});
}
methodTwo() {
this.subscriptionTwo = return this.httpClient.post(myurl , mydata);
}
Now whenever mySubjectOne
fires, methodTwo
will be executed.现在每当
mySubjectOne
触发时, methodTwo
将被执行。 Once that's done, myTreatment
will run.完成后,
myTreatment
将运行。
Note that you should run methodOne
just once (to initialize the subscription), as otherwise the subscription may run multiple times.请注意,您应该只运行一次
methodOne
(以初始化订阅),否则订阅可能会运行多次。 So I suggest to move the initialization process into your constructor or maybe ngOnInit
.所以我建议将初始化过程移到你的构造函数或者
ngOnInit
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.