How to handle request on interceptor after getting the value from an observable on rxjs and angular?

血红的双手。 提交于 2019-12-23 03:15:15

问题


So I'm coming from an AngularJS background while learning Angular 5, I still can't wrap my head around observables.

I'm trying to write an HTTP interceptor for my authentication service. However when I try to get a value from the localstorage service (or any observable at this point) I'm not quite sure how to properly return the next.handle(req) method from the observable after getting the data (using subscribe?)

Here's my current code (which does not work):

@Injectable()
export class AuthinterceptorService implements HttpInterceptor {

  constructor(private storage: LocalStorage) { }

  intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
    return this.storage.getItem('authToken').subscribe(res => {
      return next.handle(req);
    });
  }    

}

Notice I'm not doing anything with the data, simply trying to return the Observable> object from within my async call

Thanks in advance for your help


回答1:


Returning an Observable inside subscribe won't do anything. You need to merge it into the chain. For example like this:

return this.storage.getItem('authToken')
  .mergeMap(res => next.handle(req));


来源:https://stackoverflow.com/questions/50688598/how-to-handle-request-on-interceptor-after-getting-the-value-from-an-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!