简体   繁体   中英

HttpInterCepter in ionic 3 + ionic storage jwt token

I have create http interceptor class for adding headers to my rest api and the http interceptor class is working well but when i incorporate ionic storage with http interceptor the it arise some problem.i know that storage is async.so http interceptor don't get the value from storage or it execute before getting value from storage.

my app flow like this->

 1:user enter the mobile number
 2:check the mobile number in the database
 3:if(found) send otp
 4:verify otp 
 5:send api token to application
 6:now i store the api token into storage.

my code is given below..i want to implement http interceptor

token interceptor.ts

    import {HttpClient, HttpInterceptor} from '@angular/common/http';
import {Injectable, Injector} from '@angular/core';
import {HttpRequest,HttpHandler,HttpEvent} from "@angular/common/http";
import  {Observable} from "rxjs/Observable";
import {AuthServiceProvider} from "../auth-service/auth-service";




import {Storage} from "@ionic/storage";

/*
  Generated class for the TokenIntercepterProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class TokenIntercepterProvider implements HttpInterceptor{

  apiToken:any;
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


    this.auth.getToken('apiToken')
      .then(data=>{
        console.log(data);
        this.apiToken=data;
      })
      .catch()

    const changedReq = req.clone({
      headers: req.headers.set('Authorization', 'Bearer ' + this.apiToken)});
    return next.handle(changedReq);

  }

  constructor(private inj:Injector,
              public auth:AuthServiceProvider) {

  }

}

auth service.ts

  async getToken(key){

    return await this.storage.get(key);

  }

  setToken(token){

    this.storage.set('apiToken',token);
  }

any work around..pls help..i just need api token from storage then only it added to intercepter

Ionic storage too much similar to window localStorage. You can use window localStorage also. I am providing solution for your problem and it works for ionic 3/4 http interceptor. Create token service and get its as observable. Follow the method...

Note: When you put this question it might be version Angular 5, ionic 3, and Rxjs lower version other than 6 but currently I am using Angular 6, Ionic 4, Rxjs 6

token.service.ts

 import { Storage } from '@ionic/storage';
 import { Injectable } from '@angular/core';
 import { from } from 'rxjs';

 @Injectable({
  providedIn: 'root'
 })
 export class TokenService {
  constructor(private storage: Storage) { }

 getToken() {
 return this.storage.ready().then(() => {
  return this.storage.get('token')
    .then(
      data => {
        return data;
      },
      error => console.error(error)
    );
  });
}

 getTokenAsObservable() {
  return from(this.getToken());
 }
}

http-token-interceptor.service.ts *Note: inject tokenService and follow the interceptor method

 export class HttpTokenInterceptorService implements HttpInterceptor {
  constructor(private tokenService: TokenService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): 
  Observable<HttpEvent<any>> {
  const tokenObservable =  this.tokenService.getTokenAsObservable()
  .pipe(
    map(token => (
    request = request.clone({
      setHeaders: {
        Authorization: 'Bearer ' + token
      }
     })
   ))
   );
 return tokenObservable.pipe(
  flatMap(req => next.handle(req))
 );
 }
}

In app.module.ts

providers: [
     {
     provide: HTTP_INTERCEPTORS,
     useClass: HttpTokenInterceptorService,
     multi: true
    },
 ]

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