Reputation: 27
my question center around this peace of code
@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);
},
);
}
}
i didn't understant the need of the operator first(), the author gave that explanation
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
the select selector returns an observable and is supposed to fires every time the state changes in the store, but where is the subscription to the observable returned by select
link to the originale article : https://antonyderham.me/post/angular-ngrx-auth-interceptor/
Upvotes: 1
Views: 223
Reputation: 13539
it's internal implementation of the interceptor handler. It subscribes to result of intercept
method and uses an emitted value to send a request.
it looks similar to
const interceptor = new TokenInterceptor(store);
interceptor.intercept(new HttpRequest('POST', '/test', {}), backend).subscribe();
but it's under the hood of angular.
Upvotes: 1