【发布时间】: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