为什么 Ngrx 选择器在没有订阅的情况下触发?
why the Ngrx selector fires without subscription?
我的问题围绕着代码的和平
@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);
},
);
}
}
没看懂operator 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 select 或 returns 一个可观察对象,应该在每次状态改变时触发
存储,但是对 select
返回的可观察对象的订阅在哪里
link转至原文:https://antonyderham.me/post/angular-ngrx-auth-interceptor/
它是拦截器处理程序的内部实现。它订阅 intercept
方法的结果并使用发出的值发送请求。
它看起来类似于
const interceptor = new TokenInterceptor(store);
interceptor.intercept(new HttpRequest('POST', '/test', {}), backend).subscribe();
但它在 angular 的幕后。
我的问题围绕着代码的和平
@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);
},
);
}
}
没看懂operator 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 select 或 returns 一个可观察对象,应该在每次状态改变时触发 存储,但是对 select
返回的可观察对象的订阅在哪里link转至原文:https://antonyderham.me/post/angular-ngrx-auth-interceptor/
它是拦截器处理程序的内部实现。它订阅 intercept
方法的结果并使用发出的值发送请求。
它看起来类似于
const interceptor = new TokenInterceptor(store);
interceptor.intercept(new HttpRequest('POST', '/test', {}), backend).subscribe();
但它在 angular 的幕后。