我的Angular 6拦截器出现问题。我已经将代码从Angular 5.x迁移到了6.0。和rxjs 5.x到6.x。当我尝试创建一个新的用户帐户时,该请求似乎被调用了两次。我知道这是因为我将错误记录到控制台。我注意到当我尝试从firebase auth获取Id令牌时,我得到了重复信息,请参见下面的代码片段。
intercept (request: HttpRequest<any>, next: HttpHandler): observable<HttpEvent<any>> {
return this.auth.getIdToken().pipe(
mergeMap((token: any) => {
if (token) {
request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
}
return next.handle(request).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
if ((err.status === 401) || (err.status === 403)) {
this.router.navigate([WellknownRoutesConstants.SIGN_IN], { queryParams: { returnUrl: this.router.routerState.snapshot.url }});
}
}
})
);
}));
}
getIdToken (): Observable<any> {
return ngFireAuth.authState.pipe(
tap((user) => {
if (user) {
return observableOf(user.getIdToken());
} else {
return observableOf;
}
}),
catchError(observableOf)
);
}
答案 0 :(得分:4)
格兰特的回答很好,但是有一个问题。
如果用户注销,则auth.idToken
会发出一个值,因为令牌值更改为null
。请求对象保持不变(但仍处于初始化状态),因此重复了HTTP请求。
我使用take(1)
仅采用auth.idToken
Observable发出的第一个值。我还更改为switchMap
(请参阅take):
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.auth.idToken.pipe(
take(1), // <-------------- only emit the first value!
switchMap((token: any) => {
if (token) {
request = request.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
}
return next.handle(request);
})
);
}
答案 1 :(得分:2)
自从升级到Angular 6 / RxJS 6以来,这对我有用。这是我的拦截器:
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(
private auth: AngularFireAuth
) {
console.log('token interceptor constructor');
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.auth.idToken.pipe(
mergeMap((token: any) => {
console.log(token);
if (token) {
request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
}
return next.handle(request);
}));
}
}