我创建了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) {
}
}
身份验证服务.ts
async getToken(key){
return await this.storage.get(key);
}
setToken(token){
this.storage.set('apiToken',token);
}
周围的任何工作。。请帮忙。。我只需要存储中的api令牌,然后只将其添加到拦截器中
离子存储与window localStorage过于相似。您也可以使用窗口localStorage。我正在为您的问题提供解决方案,它适用于ionic 3/4 http拦截器。创建令牌服务并将其视为可观察的。按照方法。。。
注意:当你提出这个问题时,它可能是Angular 5、ionic 3和Rxjs版本,而不是6,但目前我使用的是Angular 6、ionic 4、Rxjs6
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*注:注入tokenService并遵循拦截器方法
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))
);
}
}
在app.module.ts 中
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpTokenInterceptorService,
multi: true
},
]