我正在使用HttpInterceptor
Angular 的 api,HttpClientModule
现在陷入了困境。这是我的用例。
在我的应用程序中,如果任何服务进行 http 调用,我想在它之前进行另一个静默 http 调用,并希望将其结果存储在本地。静默调用完成后,只有我会继续服务的 http 调用并返回其结果。
这就是我正在做的事情。(使用 HttpInterceptor)
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.match(/api\//)) { // api call
http.post('/auth/silentCall', {user: 123}).subscribe(
(data) => {
console.log(data);
const clone = req.clone({ setHeaders: { 'Authorization ': tokenService.getToken() } });
return next.handle(clone).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log('Service's call response');
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
console.log('Network call err', err);
}
});
},
(err) => {
if (err instanceof HttpErrorResponse) {
return Observable.throw(err);
}
);
} else {
console.log('Not an api call..It's an auth call');
return next.handle(req); // call original auth request.
}
}
现在,上面代码的问题是,它成功地执行了内部静默调用,但之后再没有调用原始的 api 调用。所以服务一直在等待。