我在最后幾個小時學習了有關 jwt 重繪 令牌的教程,但似乎代碼有點舊,并且有一些更改。所以我構建了一個攔截器,它的 Observable 出現了問題,我不知道如何修復它。
錯誤是:
“函式缺少結束回傳陳述句,回傳型別不包括‘未定義’”
我知道它出現是因為我的 Observable 沒有特定的回報。
我的代碼:
intercept(request : HttpRequest<any>, next : HttpHandler): Observable<HttpEvent<any>>
{
// Check if the user is logging in for the first time
return next.handle(this.attachTokenToRequest(request)).pipe(
tap((event : HttpEvent<any>) => {
if(event instanceof HttpResponse)
{
console.log("Success");
}
}),
catchError((err) : Observable<any> => { //Here comes the error message
if(err instanceof HttpErrorResponse) {
switch((<HttpErrorResponse>err).status)
{
case 401:
console.log("Token expired. Attempting refresh ...");
return this.handleHttpResponseError(request, next);
case 400:
return <any>this.acct.logout();
}
} else
{
return throwError(this.handleError);
}
//I think here should be a return but I don't know which kind, tried already a few ones
})
);
}
我也可以給你看教程的原始代碼,這是鏈接:
https://dev.azure.com/Techhowdy/_git/NG_Core_AuthRTDB?path=/ClientApp/src/app/_helpers/jwt.Interceptor.ts
uj5u.com熱心網友回復:
通過回傳新的 observable 或拋出錯誤來捕獲要處理的 observable 上的錯誤。捕獲錯誤
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Check if the user is logging in for the first time
return next.handle(this.attachTokenToRequest(request)).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log('Success');
}
}),
catchError((err): Observable<any> => {
if (err instanceof HttpErrorResponse && err.status === 401) return this.handleHttpResponseError(request, next);
/**
* I think the problem is here, the logout function does not return an observable and you can do like this
*/
if (err instanceof HttpErrorResponse && err.status === 400) this.acct.logout();
return throwError(this.handleError);
}),
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369132.html
