return 一个可观察到的正确

return an observable correct

我在最后几个小时学习了有关 jwt 刷新令牌的教程,但代码似乎有点旧并且有一些更改。所以我构建了一个拦截器,它遇到了 Observable 的问题,我不知道如何修复它。

错误是:

"Function lacks ending return statement and return type does not include 'undefined'"

我知道它会出现,因为我的 Observable 没有特定的 return。

我的代码:

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

    }

我也可以向您展示教程的原始代码,即 link:

https://dev.azure.com/Techhowdy/_git/NG_Core_AuthRTDB?path=/ClientApp/src/app/_helpers/jwt.Interceptor.ts

捕获要通过返回新的可观察对象或抛出错误来处理的可观察对象的错误。 catchError

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