如何在 Observable 管道中捕获错误?
How to catchError on Observable's pipe?
这是我的代码:
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'));
})
);
}
}
但我在 catchError(() => {
上遇到错误:类型为“() => void”的参数不可分配给类型为“(err: any, caught: Observable) =>”的参数可观察输入'。
类型 'void' 不可分配给类型 'ObservableInput'
在这种情况下我应该使用什么?
再次使用语法。使用正确的一个,return 运算符中的正确类型。
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);
})
);
}
}
这是我的代码:
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'));
})
);
}
}
但我在 catchError(() => {
上遇到错误:类型为“() => void”的参数不可分配给类型为“(err: any, caught: Observable) =>”的参数可观察输入'。
类型 'void' 不可分配给类型 'ObservableInput'
在这种情况下我应该使用什么?
再次使用语法。使用正确的一个,return 运算符中的正确类型。
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);
})
);
}
}