Angular 组件调用多个API时只调用一次侦听器

Angular 组件调用多个API时只调用一次侦听器,angular,Angular,我在一个组件中有多个API,其中on token expire拦截器运行多次,例如,如果我在一个组件中有4个GET API,那么4次拦截器将在token expire上运行 下面是拦截器的代码 my.httpInterceptor.ts 导入{ 注射的 }从“@角度/核心”; 进口{ 水龙头 }来自“rxjs/运营商”; 进口{ ToastyService, 祝酒辞 }来自“ng2 toasty”; 进口{ 路由器 }从“@角度/路由器”; 进口{ _扔 }来自“rxjs/可观察/抛出”; 导

我在一个组件中有多个API,其中on token expire拦截器运行多次,例如,如果我在一个组件中有4个GET API,那么4次拦截器将在token expire上运行

下面是拦截器的代码

my.httpInterceptor.ts

导入{
注射的
}从“@角度/核心”;
进口{
水龙头
}来自“rxjs/运营商”;
进口{
ToastyService,
祝酒辞
}来自“ng2 toasty”;
进口{
路由器
}从“@角度/路由器”;
进口{
_扔
}来自“rxjs/可观察/抛出”;
导入'rxjs/add/operator/do';
导入“rxjs/可观察”;
进口{
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse,
HttpErrorResponse,
HttpHeader
}来自“@angular/common/http”;
进口{
可观察
}来自“rxjs/可观察”;
@可注射()
导出类MyInterceptor实现HttpInterceptor{
构造函数(专用路由器:路由器,专用ToAsySysteService:ToAsysteService,){}
//将为所有http调用调用的函数
拦截(
请求:HttpRequest,
下一步:HttpHandler
):可观察>{
//如何更新请求参数
if(JSON.parse(localStorage.getItem('userDetails')){
让authToken=JSON.parse(localStorage.getItem('userDetails');
if(authToken.currentUserToken!=null){
const authReq=request.clone({
标题:新的HttpHeaders({
“内容类型”:“应用程序/json”,
“授权”:“承载者”+authToken.currentUserToken
})
});
返回next.handle(authReq)
.catch((错误)=>{
如果(错误){
设errorCodes=[404500422412409];
if(错误代码包括(错误状态)){
让toastOptions:toastOptions={
标题:“错误”,
消息:“错误”,
showClose:没错,
超时:5000,
主题:“默认”
};
toastOptions.msg=err.error.errors.name;
this.toasystyservice.error(toastOptions);
}
如果(错误状态===401){
这个.router.navigate(['/'])。然后((导航)=>{
//调试器;
中频(导航){
如果(this.router.url==='/')){
设置超时(()=>{
让toastOptions:toastOptions={
标题:“会话已过期”,
msg:“请重新登录以访问”,
showClose:没错,
超时:5000,
主题:'默认',
}
//toastOptions.msg=“会话已过期”;
this.toasystyservice.error(toastOptions);
});
}
}
});
}
返回抛出(错误消息);
}
});
}
}否则{
const updatedRequest=request.clone({
标题:新的HttpHeaders({
“内容类型”:“应用程序/json”,
})
});
返回next.handle(updateRequest)
}
}

}
将为所有传出http请求调用拦截器。但是,您可以筛选要应用逻辑的请求URL:

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor(private router: Router, private toastyService: ToastyService) {
  }

  //The API you want to intercept its requests (you could take it from a global constants file)
  API_URL = "http://www.example.com/host/to/intercept";

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

    //only get the token from localStorage when the request points to the API that needs authorization
    if (request.url === this.API_URL) {
      let userDetails = localStorage.getItem('userDetails');
      if (userDetails != null) {
        let authToken = JSON.parse(userDetails);
        if (authToken.currentUserToken != null) {
          const authReq = request.clone({
            headers: new HttpHeaders({
              'Content-Type': 'application/json',
              'Authorization': 'Bearer' + authToken.currentUserToken
            })
          });
          return next.handle(authReq)
          .catch((err) => {
            if (err) {
              let errorCodes = [404, 500, 422, 412, 424, 409];
              if (errorCodes.includes(err.status)) {
                let toastOptions: ToastOptions = {
                  title: "Error",
                  msg: "Error",
                  showClose: true,
                  timeout: 5000,
                  theme: 'default'
                };
                toastOptions.msg = err.error.errors.name;
                this.toastyService.error(toastOptions);
              }
              if (err.status === 401) {
                this.router.navigate(['/']).then((nav) => {
                  // debugger;
                  if (nav) {
                    if (this.router.url === '/') {
                      setTimeout(() => {
                        let toastOptions: ToastOptions = {
                          title: "Session Expired",
                          msg: "Please login again to access",
                          showClose: true,
                          timeout: 5000,
                          theme: 'default',
                        }
                        // toastOptions.msg = "Session Expired";
                        this.toastyService.error(toastOptions);
                      });
                    }
                  }
                });
              }
              return _throw(err.message);
            }
          });
        }
      } else {
        const updatedRequest = request.clone({
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
          })
        });
        return next.handle(updatedRequest);
      }
    }
  }
}
@Injectable()
导出类MyInterceptor实现HttpInterceptor{
构造器(专用路由器:路由器,专用ToasyService:ToasyService){
}
//要拦截其请求的API(可以从全局常量文件获取)
API_URL=”http://www.example.com/host/to/intercept";
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
//仅当请求指向需要授权的API时,才从localStorage获取令牌
if(request.url==this.API\u url){
让userDetails=localStorage.getItem('userDetails');
if(userDetails!=null){
让authToken=JSON.parse(userDetails);
if(authToken.currentUserToken!=null){
const authReq=request.clone({
标题:新的HttpHeaders({
“内容类型”:“应用程序/json”,
“授权”:“承载者”+authToken.currentUserToken
})
});
返回next.handle(authReq)
.catch((错误)=>{
如果(错误){
设errorCodes=[404500422412409];
if(错误代码包括(错误状态)){
让toastOptions:toastOptions={
标题:“错误”,
消息:“错误”,
showClose:没错,
超时:5000,
主题:“默认”
};
toastOptions.msg=err.error.errors.name;
this.toasystyservice.error(toastOptions);
}
如果(错误状态===401){
这个.router.navigate(['/'])。然后((导航)=>{
//调试器;
中频(导航){
如果(this.router.url==='/')){
设置超时(()=>{
让toastOptions:toastOptions={
标题:“会话已过期”,
msg:“请重新登录以访问”,
showClose:没错,
超时:5000,
主题:'默认',
}
//toastOptions.msg=“会话已过期”;
this.toasystyservice.error(toastOptions);
});
}
}
});
}
返回抛出(错误消息);
}
});
}
}否则{
const updatedRequest=request.clone({
标题:新的HttpHeaders({
“内容类型”:“应用程序/json”,
})
});