I am trying to write an HTTP interceptor to add an 'access level' parameter to the request. I am trying to get the value from an observable currentAccessLevel$. However, the observable is not returned correctly and the interceptor breaks the entire request cycle.
This question already has an answer here and here , however, the accepted answers do not seem to be working in Angular 8. I am not sure if I'm doing something wrong or if there was some sort of change made to interceptors in Angular 8.
I also tried using switchMap, flatMap, and mergeMap.
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { AuthService } from 'src/app/services/auth/auth.service';
@Injectable()
export class AccessLevelInterceptor implements HttpInterceptor {
private accessLevel: string;
constructor(private authService: AuthService) { }
// Intercept HTTP Requests
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get current value of access level observable from authentication service
return this.authService.currentAccessLevel$
.mergeMap(res => next.handle(request));
}
}
The currentAccessLevel$ is a string value created in a service as a BehaviorSubject and then converted to an Observable. That way the current value of the string can be shared across multiple components.
// Create a BehaviorSubject to track and share updates to currentAccessLevel value
private currentAccessLevel: string;
currentAccessLevelSubject: BehaviorSubject<string> = new BehaviorSubject(this.currentAccessLevel);
currentAccessLevel$ = this.currentAccessLevelSubject.asObservable();
Yes, this is not working anymore since Rxjs 5.5. You need to use pipe method to concatenate operators:
return this.authService.currentAccessLevel$
.pipe(mergeMap(res => next.handle(request)));
Take a look here to learn more about piping.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.