我需要在拦截器中向请求添加令牌。我不断收到错误消息
core.js:1673 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
at subscribeTo (subscribeTo.js:41)
at subscribeToResult (subscribeToResult.js:11)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub (mergeMap.js:73)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext (mergeMap.js:68)
at
获取令牌是异步操作
在AuthService.ts中,我有
getToken2() {
if (firebase.auth().currentUser) {
return from(firebase.auth().currentUser.getIdToken());
} else {
return null;
}
}
我的拦截器如下所示,但我不断收到错误消息
import {
HttpInterceptor,HttpRequest,HttpHandler,HttpEvent} from "@angular/common/http";
import { Observable } from "rxjs";
import { mergeMap, switchMap, flatMap } from "rxjs/operators";
import { Injectable } from "@angular/core";
import { AuthService } from "../auth/auth.service";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const tokenObservable = this.authService.getToken2(); // if there is a user logged in
if (tokenObservable) {
tokenObservable.pipe(
switchMap(token => {
const copiedReq = req.clone({
params: req.params.set("auth", token)
});
return next.handle(copiedReq);
})
);
} else {
return next.handle(req);
}
}
}
答案 0 :(得分:1)
知道了,这是一个非常愚蠢的错误
我在返回this.authService.getToken2()。pipe(
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
console.log("Attempt Intercept");
if (req.method === "GET") {
return next.handle(req);
}
return this.authService.getToken2().pipe(
switchMap(token => {
console.log("[AuthInterceptro]: token ", token);
const copiedReq = req.clone({
// headers: req.headers.append('', '')
params: req.params.set("auth", token)
});
return next.handle(copiedReq);
})
);
}
}