为什么Ngrx选择器会在没有订阅的情况下触发?

时间:2020-04-27 14:18:12

标签: angular observable ngrx subscription ngrx-store

我的问题中心围绕着代码的和平

@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,并且应该在每次状态改变时触发。 存储,但是select返回的对observable的订阅在哪里

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

1 个答案:

答案 0 :(得分:1)

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

它看起来类似于

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

但是它在有角度的掩盖下。