从rxjs和angular的可观察值中获取值后,如何处理拦截器上的请求? [英] How to handle request on interceptor after getting the value from an observable on rxjs and angular?

查看:107
本文介绍了从rxjs和angular的可观察值中获取值后,如何处理拦截器上的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在学习Angular 5时来自AngularJS背景,我仍然无法将自己的头围在可观察对象上.

我正在尝试为我的身份验证服务编写HTTP拦截器.但是,当我尝试从localstorage服务(或此时的任何可观察对象)获取值时,我不太确定如何在获取数据后(使用订阅?)从可观察对象正确返回next.handle(req)方法./p>

这是我当前的代码(无效):

@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);
    });
  }    

}

注意,我对数据不做任何事情,只是尝试从异步调用中返回Observable>对象

预先感谢您的帮助

解决方案

返回subscribe内部的Observable不会执行任何操作.您需要将其合并到链中.例如这样的

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

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

解决方案

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));

这篇关于从rxjs和angular的可观察值中获取值后,如何处理拦截器上的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆