简体   繁体   English

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

[英]Error building auth interceptor in Ionic + Angular

I am building an app in ionic (and angular) and i need to implement an http interceptor so when the user is logged in it adds the token to the request headers.我正在用离子(和角度)构建一个应用程序,我需要实现一个 http 拦截器,因此当用户登录时,它将令牌添加到请求标头中。

This is my auth.interceptor class (imports not shown)这是我的 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);
        }
    }
}

When i am logged and make a request to the api i get this error当我登录并向 api 发出请求时,我收到此错误

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

Am i making something wrong i think the cause of the error is this because if i am not logged in the error doesn't occur.我做错了什么我认为错误的原因是因为如果我没有登录,则不会发生错误。

I have already searched and couldn't find anything that helped.我已经搜索过,找不到任何有帮助的东西。 This code is identical to what i have in another angular application and in that app it works.此代码与我在另一个 angular 应用程序中的代码相同,并且在该应用程序中它可以工作。

Thanks in advance to anyone who may help.提前感谢任何可能提供帮助的人。

Try this way: import:试试这个方法:导入:

   import { throwError } from 'rjxs';

and

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

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM