我正在使用Angular HTTP拦截器将令牌添加到标头。但是,当尝试获取令牌时,我收到此错误:
Observable.js:54 RangeError:超出了最大调用堆栈大小
我尝试重写代码并分离出http请求以使用其他类获取令牌。现在,我无法从服务器获得令牌的响应。我已经验证了Web服务可以正常工作,并使用邮递员返回了令牌。
token.interceptor.ts
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
//private authService: AuthService;
constructor(public injector: Injector) {}
private addToken() {
const authService = this.injector.get(AuthService);
authService.getAuthToken().pipe(map(e=> {
//console.log('e: ' + e);
localStorage.setItem("token", e);
}));
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token = localStorage.getItem('token');
if (!token) {
this.addToken();
let token = localStorage.getItem('token');
req = req.clone({ setHeaders: { Authorization: 'Bearer ' + token }})
return next.handle(req);
}
else{
return next.handle(req);
}
}
}
//auth.service.ts
@Injectable()
export class AuthService {
private endpoint = environment.apiUrl;
constructor(private http: HttpClient) {
}
getAuthToken() {
var req: string = '{"Username": "ff","Password": "XYZ123"}';
return this.http.post<string>(this.endpoint + 'Token/RequestToken', req).pipe(map((data => {return data})));
}
}
预期结果应包括保存在本地存储中的返回令牌,并且不应返回范围错误。