使用Angular HttpInterceptor时,RxJS BehaviorSubject无法正确更新

时间:2019-11-06 21:37:36

标签: angular rxjs angular-http-interceptors

我正在尝试在Angular 8中设置HttpInterceptor,以便在前端无法到达后端时提醒用户。我将其设置如下:

@Injectable({ providedIn: "root" })
export class HttpErrorInterceptor implements HttpInterceptor {

    private errorCounterE = new BehaviorSubject(999);
    errorCounter1 = this.errorCounterE.asObservable();

    setErrorCounterE(ourvalue: number): void {
        console.log("setting value: " + ourvalue);
        this.errorCounterE.next(ourvalue);
    }


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log("aaa: " + this.errorCounterE.getValue());

        return next.handle(request)
            .pipe(
                retry(1),
                catchError((error: HttpErrorResponse) => {                  

                    console.log("ccc: " + this.errorCounterE.getValue());
                    this.setErrorCounterE(this.errorCounterE.getValue() + 1);
                    console.log("ddd: " + this.errorCounterE.getValue());                    

                    return throwError(errorMessage);
                })
            )}}

通过我的app.module提供程序设置如下:

providers: [
        emailCallService,
        securityCallService,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: HttpErrorInterceptor,
            multi: true
        }
    ],

我现在通过一个简单的按钮按下它,在后端组件处于关闭状态(这样肯定会引发错误),在这样的组件类中调用它:

export class ActiveMachinesComponent implements OnInit {
  constructor(private ecs: emailCallService, private scs: securityCallService, private hei: HttpErrorInterceptor) {
    this.emailErrorCount = 54321;
  }

private emailErrorCount: number;

 ngOnInit() {   
    console.log("error counter is now..." + this.emailErrorCount);
    this.hei.errorCounter1.subscribe(ourcount => this.emailErrorCount = ourcount);
    console.log("error counter is now..." + this.emailErrorCount); 
  }


buttonpress(): any { 
    console.log("------------");
    this.hei.errorCounter1.subscribe(thatvalue => {
      this.emailErrorCount = thatvalue
    });
    let t = this.emailErrorCount;
    console.log(t);
    console.log("------------");

    //then call it
    this.ecs.checkEmailService().subscribe((result) => {
        [another component makes an http call here, returning an observable.] 
    })
}

在页面加载时,ngInit可以正常工作,先打印54321,然后再打印999。第一个按钮推入调用在虚线之间打印999。当调用返回到拦截器时,catchError子句中的值应从999变为1000。

问题在于,如果我第二次按下该按钮,则虚线之间的数字再次为999,即使在截取的第一步中它会打印“ aaa:1000”。我以为这是由于我的组件类获得了拦截器类的一个单独的实例,但是我认为在根目录中提供该实例应该可以解决该问题并使其得以解决,因此每个人只能共享一个实例。

我在这里的最终目标是让我的错误拦截器对看到的各种不同类型的错误进行计数(404、403等),并根据看到的内容在不同的时间提醒用户。但是我正在组件类之外运行ngIf,这意味着我需要使该类可见我的错误计数器。有什么建议么?我将这个设置完全错误吗?

0 个答案:

没有答案