1

我按照几篇文章在 Angular 上实现 JWT 身份验证,似乎一切正常,除了检测 401 未经授权。

我想将用户重定向到登录页面,但我无法检测到 401 错误。

我有这堂课:

export class JwtInterceptor implements HttpInterceptor {

  constructor(public authService: AuthService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        console.log('HTPP REQUEST');
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          this.authService.collectFailedRequest(request);
          console.log('Login boy');
        }
      }
    });
  }
}

但不确定在哪里使用它。我有auth.service.ts哪些包含login()getToken()方法,jwt.interceptor.ts哪些包含

4

1 回答 1

1
providers: [PagerService, AuthService,
  {
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true
  }, {
    provide: HTTP_INTERCEPTORS,
    useClass: JwtInterceptor,
    multi: true
  }
]

我必须在module.app.ts. 不要忘记在拦截器中添加@Injectable()before 。export class...

于 2018-02-26T17:57:16.513 回答