Federico Xella
Federico Xella

Reputation: 137

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.

Upvotes: 0

Views: 138

Answers (1)

Sravan
Sravan

Reputation: 18647

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);
    })
  }
}

Upvotes: 1

Related Questions