Avoiding Nested Subscriptions and Passing Values to Error Handler

Is it possible to change the property of an emitted value from a Subject before passing it to another Observable? For example:

this.subscriptions.push(this.myService.mySubject.subscribe(value => {
    value.property = true;
    this.subscriptions.push(this.myOtherService.myMethod(value.propertyTwo).subscribe(value => {
    // do things with value
}, (error) => {
    // how can I still access said value in the error handler?

I push my subscriptions to a private subscriptions array so that I can unsubscribe from them in my ngOnDestroy. I'd like to get to get rid of the nested subscription in this case and was wondering if it was possible to do so?

Also, how can I still access the value variable in the error handler of my subscription?


1 answer

  • answered 2018-02-13 03:01 Fan Cheung

    Chain them up with switchMap and handle error with catch. In well written observable chains usually you don't need many subscriptions

    this.subscriptions.push(this.myService.mySubject.switchMap(value => {
    value.property = true;
    return this.myOtherService.myMethod(value.propertyTwo)})