How to do a service call in interceptor & execute the next steps only once that is completed- async call to a service in Angular Interceptor

huangapple go评论59阅读模式
英文:

How to do a service call in interceptor & execute the next steps only once that is completed- async call to a service in Angular Interceptor

问题

我正在尝试在拦截器中使用以下代码段进行服务调用-进入图像描述
但在运行后,我得到以下错误-进入图像描述

所以当我使用 .then() 并等待服务完成,然后才执行此 .then() 内的其他代码片段时,它会出现此错误,因为管道未定义。但是,如果我简单地使用 this.authservice.refreshToken(); 而不等待任何东西,它将在不等待此服务调用完成的情况下执行下一组行,并且不会出现任何错误。有没有关于如何在拦截器中异步调用服务调用方法的想法?

英文:

I am trying to do a service call in the interceptor with below code piece-enter image description here
However i am getting below error after running it-enter image description here

SO when i put a .then() & wait for the service to get over & then only execute the other piece of code inside this .then() its giving this error as pipe is undefined. However if i simply put a this.authservice.refreshToken(); without any wait it will execute the next set of lines without waiting for this service call to complete & work fine without giving any error. Any idea how to work on an interceptor where we can call a service call method asynchronously?

答案1

得分: 1

你必须从拦截器的intercept方法中返回observable。在你的代码中,将next.handle(... 放在 .then( 回调中执行,这就是为什么它不起作用的原因。

尝试以这种方式重新组织拦截器逻辑:

const token$ = this.IsTokenExpired() ? 
   from(this.authService.refreshPingToken()) : 
   of(this.AuthToken);

return token$.pipe(
  switchMap((token) => {
    // ...用于创建“req”的逻辑
    return next.handle(req);
  }),
  tap(handleResponse)
)
英文:

you have to return observable from the intercept method. in your code return next.handle(... is done inside of .then( callback instead and that is why it doesn't work

try this way of organizing interceptor logic instead

const token$ = this.IsTokenExpired() ? 
   from(this.authService.refreshPingToken()) : 
   of(this.AuthToken);

return token$.pipe(
  switchMap((token) => {
    // ...your logic for creating "req"
    return next.handle(req);
  }),
  tap(handleResponse)
)


huangapple
  • 本文由 发表于 2023年6月13日 17:50:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76463661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定