首页 > 解决方案 > SnackBar 在 HTTPInterceptor 中使用时不显示

问题描述

我正在尝试编写一个全局 HTTP 拦截器,它拦截所有 HTTP 响应,检查响应并(如果满足某些条件)显示一个快餐栏。

我似乎无法让小吃店显示。如果我在 .open() 行设置断点,我会看到小吃栏出现片刻,但没有任何文本且偏离中心。

拦截器:

import { Injectable, Injector, NgZone } from '@angular/core';
import {    
    HttpEvent,
    HttpHandler,
    HttpInterceptor,
    HttpRequest,
    HttpResponse,
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';

import { MatSnackBar } from '@angular/material';
//import { of } from 'rxjs/observable/of';

@Injectable()
export class TMCErrorHttpInterceptor implements HttpInterceptor {
    constructor(public snackBar: MatSnackBar,private injector: Injector, private zone: NgZone){}
    /**
      * @param HttpRequest<any> request - The intercepted request
      * @param HttpHandler next - The next interceptor in the pipeline
      * @return Observable<HttpEvent<any>>
      */
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        return next.handle(request)
            // add error handling
            .pipe(
                tap(event => {
                    if (event instanceof HttpResponse) {                        
                        if (this.isError(event.body)){
                            this.handleError(event.body);                                          
                        }
                    }
                }, error => {
                    console.error('NICE ERROR', error)
                })
            );
    }
    isError(response: any): any {
        return (typeof (response) == "object"
            && typeof (response.MESSAGE) != "undefined"
            && typeof (response.STATUS) != "undefined"
            && typeof (response.CODE) != "undefined"
            && response.STATUS === "error"
        );
    }
    handleError(error: any): any {
        this.snackBar = this.injector.get(MatSnackBar);
        this.zone.run(() => {
            this.snackBar.open("hiiiiii");
          });
    }
}

我试过取出该区域,而不是使用注射器。没变。

标签: angularangular-materialangular6snackbar

解决方案


所以我以某种方式偶然发现了答案,克隆请求使小吃店正常工作。奇怪的。

我理解从可修改性/可链接性的角度克隆请求的必要性,但要影响小吃店,需要比我更好的头脑来解释。

所以总而言之,对于那些徘徊在这个奇怪的森林尼克的人来说,将这一行添加到拦截()函数的顶部使其工作:

请求 = request.clone();


推荐阅读