简体   繁体   中英

Error response break valueChanges [Angular2]

When I subscirbe to form and wait for value changes that break if I resonse is error from my service...

Here is code:

constructor(private fb: FormBuilder, private bankService: BankService) {
        this.page = 1;

        this.filter = this.fb.group({
            text: ['', []],
            bankC: ['', []]
        });

        this.filter.valueChanges
            // wait for a pause in typing of 200ms then emit the last value
            .debounceTime(200)
            // only accept values that don't repeat themselves
            .distinctUntilChanged()
            // map that to an observable HTTP request, using the TickerLoad
            // service and switch to that
            // observable. That means unsubscribing from any previous HTTP request
            // (cancelling it), and subscribing to the newly returned on here.
            .switchMap((val: any) => {
                return bankService.getCountry(val.bankC)
            })
            .subscribe((res) => {
                console.log(res);
            },
             (err) => {
                 console.log(err);
             });
            // send an empty array to tickers whenever clear emits by
            // merging in a the stream of clear events mapped to an
            // empty array.
    }

Edit

I found what couse problem, it is inside http intreceptor:

intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            if (err.status == 401) {
                this._router.navigate(['']);
                return Observable.throw(err);
                //&& !_.endsWith(err.url, 'api/auth/login')
            } else {
               return Observable.throw(err);
            }
        });

    }

It is this part: return Observable.throw(err);

How can I return error without braking subscription.

If you want to resubscribe to the source Observable use retry() operator before subscribe() :

...
.switchMap((val: any) => {
    return bankService.getCountry(val.bankC)
})
.retry(-1) // resubscribe forever
.subscribe((res) => {
    console.log(res);
}, ...

I know it's too late but try using -

return throwError(err);

Or you can also throw a recovery observable.

return of(null);

Or

return EMPTY;

You can also use RxJs pipe operator to chain multiple catchError operators like this -

.pipe(
    catchError((err) => throwError(err)),
    catchError((err) => of([])
);

One to throw a recovery error observable and other one to send a recovery empty Observable. This way you can display error message to user and send a recovery Observable to subscribe to. This will never break the chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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