简体   繁体   English

如何使用 RxJS 处理 401 Unauthorized 响应与 Angular 8 服务中的其他错误不同?

[英]How can I handle a 401 Unauthorized response differently from other errors in an Angular 8 service using RxJS?

I have a REST API that requires a user to be identified by an access token with each call.我有一个 REST API,它要求用户在每次调用时通过访问令牌进行识别。

Each API endpoint returns a 401 UNAUTHORIZED response if the token is not provided or has expired.如果令牌未提供或已过期,则每个 API 端点都会返回 401 UNAUTHORIZED 响应。

In some cases, I am calling the APIs with a timer.在某些情况下,我使用计时器调用 API。

In my service class:在我的服务类中:

getFoo(id: String): Observable<Foo> {
  return this.http.get<Foo>(url, HTTP_OPTIONS);
}

getFooList(): Observable<Foo[]> {
  return timer(0, FIVE_MINUTES).pipe(
    switchMap(() => this.http.get<Foo[]>(url, HTTP_OPTIONS))
  );
}

and, then in my component然后在我的组件中

fooList: Foo[] = [];

ngOnInit(): void {
  this.loadFooList();
}

private loadFooList() {
  this._fooService.getFooList().subscribe(
    (fooList) =>  this.fooList = fooList,
    (err) => console.error(err)
  );
}

How can I put a check in the service itself whether I have received a 401 response or not?如何检查服务本身是否收到 401 响应? Rather than having to do this in each component that uses the service?而不是必须在使用服务的每个组件中执行此操作?

I used an interceptor.我使用了拦截器。

auth.interceptor.ts auth.interceptor.ts

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(
    private _router: Router,
  ) { }

  intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(httpRequest).pipe(
        catchError((error) => {
            if (error.status == 401) {
                this._router.navigate(['/login']);
            } else {
                return Observable.throw(error);
            }
        })
    );
  }
}

Added it as a provider in my app.module.ts在我的app.module.ts 中添加它作为提供者

@NgModule({
    providers: [{
     provide: HTTP_INTERCEPTORS,
     useClass: AuthInterceptor,
     multi: true
    },
  ],
  bootstrap: [AppComponent,]
})
export class AppModule { }

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

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