Issue
import {
HttpHandler,
HttpInterceptor,
HttpParams,
HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { exhaustMap, take } from 'rxjs/operators';
import { AuthenticationService } from './authentication.service';
@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
constructor(private authService: AuthenticationService) { }
intercept(req: HttpRequest<any>, next: HttpHandler) {
return this.authService.emitUser.pipe(
take(1),
exhaustMap((user) => {
if (!user) {
return next.handle(req);
}
const modifiedReq = req.clone({
params: new HttpParams().set('auth', user!.token!),
});
return next.handle(modifiedReq);
})
);
}
}
This is an interceptor file which modifies the request url by adding 'auth' query params and a value as a token that we get from the user object here. But I cannot understand what is happending inside the exhaustMap.
Solution
exhaustMap
is a higher order pipe operator, which subscribes to the piped observable and for (nearly) each emitted value, returns a new observable, coming from the function you passed to it.
But what should happen if the returned observable has not completed yet, but the source observable emits a new value. That's where exhaustMap
, switchMap
, concatMap
and mergeMap
differ.
In your case exhaustMap
is used, which means if a new value is coming from the source observable, but the previously mapped observable is not yet completed, the new value coming from the source observable will be ignored.
It will be ignored until the previously returned observable has completed. After that new values from the source observable will be mapped to the inner observable again.
Answered By - Fabian Strathaus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.