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

时间:2019-10-01 12:27:17

标签: angular http ionic-framework ionic4

我正在用离子(和角度)构建应用程序,我需要实现一个HTTP拦截器,因此当用户登录时,它将令牌添加到请求标头中。

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

@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.

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

我已经搜索过,找不到任何有用的信息。该代码与我在另一个角度应用程序中使用的代码相同,并且在该应用程序中可以正常工作。

在此先感谢任何可能提供帮助的人。

1 个答案:

答案 0 :(得分:0)

尝试这种方式: 导入:

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

}