javascript-使用http拦截器设置来自离子存储的默认请求标头-Angular 5-Ionic 3
作者:互联网
我正在尝试使用angular 5新的HTTP客户端在所有请求标头中设置令牌值.下面是我的代码:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from "rxjs/Observable";
import { Storage } from '@ionic/storage';
import {Globals} from '../globals/globals';
@Injectable()
export class Interceptor implements HttpInterceptor {
token: string;
constructor(private storage: Storage, private global: Globals){
this.storage.get('token').then((val) => {
this.token = val;
});
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(this.token) //undefined "only for first time on app start"
req = req.clone({
setHeaders: {
'Token': this.token,
'Version': this.global.version,
}
});
return next.handle(req);
}
}
虽然在请求标头中添加令牌很有效,但是有一个严重的异常.第一次不起作用.问题在于js异步性质,req.clone在从存储中获取令牌之前就已执行.由于离子存储还应许,那么如何首次处理这种情况?
解决方法:
您可以合并两个异步请求(获取令牌和处理请求),以在令牌准备就绪时执行稍后的操作(而不是在构造函数中获取):
// -------------------------------------------------------------------------
// Please note that I'm using lettable/pipeable operators (RxJS > 5.5.x)
// https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md
// -------------------------------------------------------------------------
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from "rxjs/Observable";
import { Storage } from '@ionic/storage';
import { Globals } from '../globals/globals';
// New imports!
import { fromPromise } from 'rxjs/observable/fromPromise';
import { mergeMap } from 'rxjs/operators/mergeMap';
@Injectable()
export class Interceptor implements HttpInterceptor {
constructor(private storage: Storage, private global: Globals){ }
getToken(): Promise<any> {
return this.storage.get('token');
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return fromPromise(this.getToken()).pipe(
mergeMap(token => {
// Use the token in the request
req = req.clone({
setHeaders: {
'Token': token,
'Version': this.global.version,
}
});
// Handle the request
return next.handle(req);
}));
}
}
标签:angular,typescript,ionic2,ionic3,javascript 来源: https://codeday.me/bug/20191025/1928509.html