Angular HTTP Interceptor 如何链接一个 observable [英] Angular HTTP Interceptor how to chain an observable
本文介绍了Angular HTTP Interceptor 如何链接一个 observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Azure AD adal 库进行身份验证.有一个调用来获取一个返回一个可观察的令牌.如何将这个 observable 添加到拦截中?在下面的例子中,如何让订阅中设置的请求作为 Observable 返回?
I am using the Azure AD adal library to do authentication. There is a call to aquire a token that returns an observable. How can this observable be added into the intercept? In the below example, how can I get the request that is set inside the subscribe to be returned as the Observable?
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.authAzureService.getAccessToken()
.subscribe(token => {
// I need this to be returned
request = this.getRequestWithHeaders(request, token);
});
// This returns the request before the access token is added
return next.handle(request);
}
推荐答案
感谢@Commecial Suicide 我找到了解决方案,那就是使用 flatMap.这是有效的代码:
Thanks to @Commecial Suicide I found the solution, which is to use a flatMap. Here is the code that worked:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let requestHandler = this.authAzureService.getAccessToken()
.flatMap(token => {
request = this.getRequestWithHeaders(request, token);
return next.handle(request);
});
return requestHandler;
}
这篇关于Angular HTTP Interceptor 如何链接一个 observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文