首页 > 解决方案 > Interrupt sequential concatMap calls after error happens in one of them

问题描述

I have a view in my program with data that's hierarchical, so I need to do secuencial calls to the data base in order to fill in the appropiate data structures and show the view, if one of these calls fail I want to interrupt them.

I'm new to Angular so I researched a lot on the internet and found out that nested subscribes are a bad practice and should be avoided, so I used concatMap. Now, how do I interrupt the secuence of concatMaps after the preview one fails?

This is my code:

 getData() {        
        this.service.httpCall(null,
            url + '/test/getallprovinces').pipe(
            tap( (responsePro) => {
                if (responsePro.type === 'success') {
                      //fill in data structures
                } else {
                   //handle error and interrupt
                    throwError("error ");
                }}),
            concatMap(() => this.service.httpCall(null, url + '/test/getallcantons')),
            tap((responseCanton) => {
                if (responseCanton.type === 'success') {
                   //fill in data structures
                } else {   
                   //handle error  and interrupt               
                    throwError("error on cantons");
                }
            }),
            concatMap(() => this.service.httpCall(null, url + '/test/getalldistricts')),
            tap(responseDis => {
                if (responseDis.type === 'success') {
                    //fill in data structures
                } else {
                     //handle error  and interrupt
                    throwError("error on districts");
                }
            }))
            .subscribe(
                () => {},
                error => {console.log("something happened", error)}
                );
    }

Right now if an error happens it jumps to the next concatMap call and since there's no data it tries to fill the data structues and throws an ugly error there (pushing to an empty arra). I want to interrupt the call using trhowError

Edit: I've found the solution thanks in part to Joshua McCarthy. I was using throwError that returns an observable and continues execution. Instead I should've trhown a plain old JS exception inside the tap. Now it does interrupt the higher-order observables.

标签: angularasynchronousrxjs

解决方案


Try to add catchError() at the end of the pipe. There you can print to console log and return EMPTY. This should interrupt the observable chain the moment am error notification is emitted.


推荐阅读