Home > Net >  How to catchError on Observable's pipe?
How to catchError on Observable's pipe?

Time:04-15

Here's my code:

refreshToken(): Observable<any> {
    if (this.refreshTokenInProgress) {
        return new Observable(observer => {
            this.tokenRefreshed$.subscribe(() => {
                observer.next();
                observer.complete();
            });
        });
    } else {
        this.refreshTokenInProgress = true;

        return this.api.refreshToken().pipe(
            tap(res => {
                this.api.setAccessToken(res.access_token);
                this.refreshTokenInProgress = false;
                this.tokenRefreshedSource.next(true);
            }),
            catchError(() => {
                this.refreshTokenInProgress = false;
                this.ngZone.run(() => this.router.navigateByUrl('/account/signin'));
            })
        );
    }
}

But I got error on catchError(() => {: Argument of type '() => void' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput'. Type 'void' is not assignable to type 'ObservableInput'

What should I use in this case?

CodePudding user response:

Again with the syntax. Use the correct one, and return the correct types in the operators.

refreshToken(): Observable<any> {
    if (this.refreshTokenInProgress) {
      return this.tokenRefreshed$.pipe(take(1));
    } else {
        this.refreshTokenInProgress = true;

        return this.api.refreshToken().pipe(
            tap(res => {
                this.api.setAccessToken(res.access_token);
                this.refreshTokenInProgress = false;
                this.tokenRefreshedSource.next(true);
            }),
            catchError((error) => {
                this.refreshTokenInProgress = false;
                this.ngZone.run(() => this.router.navigateByUrl('/account/signin'));
                // If you want to "accept" the error
                return of(null);
                // If you want to "propagate" the error
                return throwError(error);
            })
        );
    }
}
  • Related