почему селектор Ngrx срабатывает без подписки? - PullRequest
1 голос
/ 27 апреля 2020

мой вопрос центрируется вокруг этого кода

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

Сначала я не осознавал необходимость оператора (), автор дал это объяснение

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

выбор Селектор возвращает наблюдаемое и, как предполагается, срабатывает каждый раз, когда состояние изменяется в хранилище, но где находится подписка на наблюдаемое, возвращаемая ссылкой

на оригинальную статью: https://antonyderham.me/post/angular-ngrx-auth-interceptor/

1 Ответ

1 голос
/ 05 мая 2020

это внутренняя реализация обработчика перехватчика. Он подписывается на результат метода intercept и использует отправленное значение для отправки запроса.

он похож на

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

, но находится под капотом angular.

...