【发布时间】:2018-12-19 04:16:39
【问题描述】:
我已经创建了 http 拦截器类,用于向我的 rest api 添加标头,并且 http 拦截器类运行良好,但是当我将离子存储与 http 拦截器合并时,它会出现一些问题。我知道存储是异步的。所以 http 拦截器不要'不从存储中获取值,或者在从存储中获取值之前执行。
我的应用流程是这样的->
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.
我的代码如下..我想实现http拦截器
令牌拦截器.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);
}
任何解决方法..请帮助..我只需要存储中的 api 令牌,然后只需将其添加到拦截器中
【问题讨论】:
标签: angular ionic-framework ionic2 ionic3