我对angular并不陌生,因此尽管我使用firebase来存储用户令牌,但在调用拦截器以修改请求标头时可以访问该令牌。
我在构造函数中分别添加了Firebase函数和HttpHandler
函数,
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private token: any = null;
constructor() {
firebase.database().ref(`currentUserDetails/${localStorage.getItem('sn')}`).once('value', (snap) => {
if(snap.exists()){
this.token = snap.val().token;
}
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(this.token) {
request = request.clone({
setHeaders: {
Authorization: this.token
}
});
}
console.log(this.token) // this is null
return next.handle(request)
}
}
问题是intercept
函数在完全执行constructor
函数之前执行。因此,this.token
为空。
我尝试使用回调函数,尝试了async await
函数,并且尝试了栈溢出中给出的solution,但此操作不成功。
是否有解决此问题的解决方案?
答案 0 :(得分:0)
由于您的once()
调用的异步性质(返回了一个承诺),我将其变为可观察的并按如下方式处理截距内的数据流:
import { from } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private token: any = null;
private token$: Observable<any>;
constructor() {
this.token$ = from(firebase.database().ref(`currentUserDetails/${localStorage.getItem('sn')}`).once('value', (snap) => {
if (snap.exists()) {
this.token = snap.val().token;
}
}));
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.token$.mergeMap(
token => {
if (token) {
request = request.clone({
setHeaders: {
Authorization: this.token
}
});
}
return next.handle(request)
}
)
}
}
来自https://medium.com/@danielcrisp/async-http-interceptors-with-angular-4-3-9e6e795da562的灵感