Vladimir Djukic
Vladimir Djukic

Reputation: 2072

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.

Upvotes: 2

Views: 1192

Answers (2)

Ankit Kumar
Ankit Kumar

Reputation: 117

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.

Upvotes: 0

martin
martin

Reputation: 96909

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);
}, ...

Upvotes: 2

Related Questions