【问题标题】:why the Ngrx selector fires without subscription?为什么 Ngrx 选择器在没有订阅的情况下触发?
【发布时间】:2020-04-27 14:18:12
【问题描述】:

我的问题围绕着这种和平的代码

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private store: Store<fromAuth.State>) {}

intercept(req: HttpRequest<any>, next: HttpHandler) {
  return this.store.select(fromAuth.getToken).pipe(
   first(),
   flatMap(token => {
    const authReq = !!token ? req.clone({
      setHeaders: { Authorization: 'Bearer ' + token },
    }) : req;
    return next.handle(authReq);
   },
  );
 }
}

我没有理解操作者first()的需要,作者给出了解释

The observable that we return from the intercept method begins with the store selector. Since this 
observable will form part of the chain when creating a new HttpClient request and subscribing, we 
don’t want to send an update everytime the token changes in the future, else the services using 
HttpClient will appear to get a new value from their request if not unsubscribed. Thus we use the 
first() operator here to only take the first value, then complete

select 选择器返回一个 observable 并且应该在每次状态改变时触发 store,但是 select 返回的 observable 的订阅在哪里

原文链接:https://antonyderham.me/post/angular-ngrx-auth-interceptor/

【问题讨论】:

    标签: angular observable ngrx subscription ngrx-store


    【解决方案1】:

    它是拦截器处理程序的内部实现。它订阅intercept 方法的结果并使用发出的值发送请求。

    看起来很像

    const interceptor = new TokenInterceptor(store);
    interceptor.intercept(new HttpRequest('POST', '/test', {}), backend).subscribe();
    

    但它在 angular 的引擎盖下。

    【讨论】:

      猜你喜欢
      • 2018-10-13
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      相关资源
      最近更新 更多