简体   繁体   English

使用 concatMap 时如何取消订阅 valueChanges?

[英]How to unsubscribe from valueChanges when using concatMap?

I'm reading an article about the rxjs concatMap operator.我正在阅读 一篇关于 rxjs concatMap运算符 的文章 This guy builds an autosave form, ie, whenever the user types a letter the data is saved using a http request这家伙建立了一个自动保存表单,即,每当用户键入一个字母时,数据就会使用 http 请求保存

this.subscription = this.form.valueChanges
      .pipe(concatMap(formValue => this.http.put(`/api/course/${courseId}`, formValue)))
      .subscribe(saveResult =>  ... handle successful save ...);

I want to be able to unsubscribe in ngOnDestroy() from the valueChanges Observable, but the this.subscription Subscription refers to the http observable.我希望能够从valueChanges Observable 在ngOnDestroy()取消订阅,但是this.subscription订阅指的是http observable。 So how can I unsubscribe from valueChanges ?那么如何取消订阅valueChanges呢?

In your ngOnDestroy function simply use your reference to the subscription.在您的 ngOnDestroy 函数中,只需使用您对订阅的引用。 When you create the observable it returns back a subscription object which exposes the unsubscribe() method.当您创建 observable 时,它​​会返回一个公开unsubscribe()方法的订阅对象。

ngOnDestroy{
this.subscription.unsubscribe();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM