Handling Expired Token From Api in Angular 4

后端 未结 2 470
迷失自我
迷失自我 2021-02-02 16:38

I need help in handling expired token in my angular application. My api has the expired time but my problem is when i forgot to log out of my angular application, after some tim

2条回答
  •  忘了有多久
    2021-02-02 17:07

    You can do this using http interceptors.

    intercept(req: HttpRequest, next: HttpHandler) {
      if(!localStorage.getItem('token'))
        return next.handle(req);
    
      // set headers
      req = req.clone({
        setHeaders: {
          'token': localStorage.getItem('token')
        }
      })
    
      return next.handle(req).do((event: HttpEvent) => {
        if(event instanceof HttpResponse){
          // if the token is valid
        }
      }, (err: any) => {
        // if the token has expired.
        if(err instanceof HttpErrorResponse){
          if(err.status === 401){
            // this is where you can do anything like navigating
            this.router.navigateByUrl('/login');
          }
        }
      });
    }
    

    Here's the full solution

提交回复
热议问题