[英]Call async function into catch from interceptor Angular
I need to call an async method to wait after call other function.在调用其他 function 后,我需要调用异步方法等待。 I'm not very expert in terms of rxjs and also I've never worked with async/await calls.我在 rxjs 方面不是很专家,而且我从未使用过异步/等待调用。
I have this logic into the interceptor我在拦截器中有这个逻辑
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.get('a-header')) {
const headers = req.headers.delete('a-header');
return next.handle(req.clone({ headers, withCredentials: true }));
}
return next.handle(req.clone({ withCredentials: true })).catch((err: Error) => {
if (!(err instanceof HttpErrorResponse) || (err as HttpErrorResponse).status !== 401) {
return throwError(err);
}
this.error.notify401Error(err);
//NEED TO AWAIT THE NEXT RESPONSE
this.callXApi(next);
//AND THEN CONTINUE WITH THIS CALL
this.redirectSignedOut();
return empty();
});
}
Note that I need to call CallXApi
, wait until finished, and then continue with redirectSignedOut
function.请注意,我需要调用CallXApi
,等待完成,然后继续使用redirectSignedOut
function。
private callXApi(): void {
const { uri } = this.config;
this.httpClient
.delete(uri, { withCredentials: true })
.subscribe(() => { console.log('completed.') }, (err) => throwError(err));
}
How can I achieve that?我怎样才能做到这一点?
UPDATE更新
I achieved this by changing the next code我通过更改下一个代码来实现这一点
return <any>next.handle(req.clone({ withCredentials: true })).catch(async (err: Error) => {
if (!(err instanceof HttpErrorResponse) || (err as HttpErrorResponse).status !== 401) {
return throwError(err);
}
this.errorEventService.notify401Error(err);
await this.callXApi();
return EMPTY;
});
Try this one:试试这个:
return next.handle(req.clone({ withCredentials: true })).catch(async (err: Error) => {
if (!(err instanceof HttpErrorResponse) || (err as HttpErrorResponse).status !== 401) {
return throwError(err);
}
this.error.notify401Error(err);
//NEED TO AWAIT THE NEXT RESPONSE
await this.callXApi(next);
//AND THEN CONTINUE WITH THIS CALL
this.redirectSignedOut();
return empty();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.