简体   繁体   中英

Do some check before http subscribe Angular

I need to check if a JWT is expired before make any http call. What is the best way to do that?

At the moment I'm using the interceptor to make the control for every request, but if the JWT is expired I get an exception because the interceptor doesn't return the request because of the redirect.

Here is an example on how to handle JWT expiry using Interceptor

Steps to follow:

  1. Create an interceptor to intercept the requests
  2. Handle the error from api using next.handle(req).catch
  3. Check the status of the error and send a specific status code for token expiry
  4. Call the create token method and add that token to headers or formdata
  5. Recall the request using next.handle(newReq)

Interceptor:

import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
  HttpErrorResponse,
  HttpParams
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/mergeMap';

import { YourService } from './your.service';

@Injectable()
export class AppInterceptor implements HttpInterceptor {
  constructor(private yourService: YourService) { }
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<any> {
    return next.handle(req).catch((event): any => {
      if (event instanceof HttpErrorResponse) {
        if (
          event.status == 'some status for token expiry'
        ) {
          return this.yourService.createToken().flatMap((res: any): any => {
              const token = res.data.ws_token;
              // send something with token and send request again   
              // set headers
               let headers = new Headers();
               headers.append('Authorization', token);
              const newReq = req.clone();
              return next.handle(newReq)
          }, err => {
            console.log(err)
              return Observable.throw(event);
          });

        }
      } else {
        return Observable.throw(event);
      }
      return Observable.throw(event);
    })
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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