Angular 8订阅了拦截器中的可观察对象

时间:2019-09-16 14:57:21

标签: angular rxjs observable interceptor angular8

我正在尝试编写HTTP拦截器,以向请求添加“访问级别”参数。我正在尝试从可观察的currentAccessLevel $获取值。但是,可观察对象未正确返回,并且拦截器中断了整个请求周期。

该问题已经有答案herehere,但是,可接受的答案似乎在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();

1 个答案:

答案 0 :(得分:2)

是的,这在Rxjs 5.5中不再起作用。您需要使用管道方法来连接运算符:

return this.authService.currentAccessLevel$
      .pipe(mergeMap(res => next.handle(request)));

看看here,以了解有关管道的更多信息。