我正在尝试编写HTTP拦截器,以向请求添加“访问级别”参数。我正在尝试从可观察的currentAccessLevel $获取值。但是,可观察对象未正确返回,并且拦截器中断了整个请求周期。
该问题已经有答案here和here,但是,可接受的答案似乎在Angular 8中不起作用。我不确定我是在做错什么还是那里是对Angular 8中的拦截器进行的某种更改。
我还尝试使用switchMap,flatMap和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));
}
}
currentAccessLevel $是在服务中作为BehaviorSubject创建的字符串值,然后将其转换为Observable。这样,字符串的当前值可以在多个组件之间共享。
// 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();
答案 0 :(得分:2)
是的,这在Rxjs 5.5中不再起作用。您需要使用管道方法来连接运算符:
return this.authService.currentAccessLevel$
.pipe(mergeMap(res => next.handle(request)));
看看here,以了解有关管道的更多信息。