在 Ionic + Angular 中构建身份验证拦截器时出错

Error building auth interceptor in Ionic + Angular

我正在用 ionic(和 angular)构建一个应用程序,我需要实现一个 http 拦截器,以便在用户登录时将令牌添加到请求中 headers。

这是我的 auth.interceptor class(导入未显示)

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(
        private auth: AuthService,
        private router: Router,
        private storage: NativeStorage,
        ) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // Clone the request to add the token header
        if(this.auth.isLoggedIn()) {
            this.storage.getItem('token').then(data => {
                const token = data as any;
                console.log(token);
                const authReq = req.clone({ setHeaders: {
                    'x-access-token': token
                  }});
                console.log(authReq);
                // Send the newly created request
                return next.handle(authReq).pipe(
                    catchError((err: HttpErrorResponse) => {
                        console.log(err);
                        // Checks if error was caused due to invalid/expired token
                        if (err instanceof HttpErrorResponse && err.status === 401) {
                            this.router.navigate(['/login'], { queryParams: { sessionExpired: true } });
                        }
                        return throwError(err);
                    }) as any
                );
            })
        }
        else {
            return next.handle(req);
        }
    }
}

当我登录并向 api 发出请求时,我收到此错误

ERROR TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

我是不是做错了什么我认为错误的原因是因为如果我没有登录就不会发生错误。

我已经搜索过了,但找不到任何有用的东西。此代码与我在另一个 angular 应用程序中的代码相同,并且在该应用程序中有效。

提前感谢任何可能提供帮助的人。

试试这个方法: 导入:

   import { throwError } from 'rjxs';

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const reqWithCredentials = req.clone({withCredentials: true});
return next.handle(reqWithCredentials)
 .pipe(
    catchError(error => {
      if (error.status === 401 || error.status === 403) {
        // handle error
        this.router.navigate(['/login'], { queryParams: { sessionExpired: true } });
      }
      return throwError(error);
    })
 );

}