在角度5和材料中使用错误处理程序时,小吃位置错误

时间:2018-04-30 13:48:07

标签: angular angular-material

我有自定义全局错误处理程序

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
    constructor(private injector: Injector) {
    }

    handleError(err: any): void {
        var route = this.injector.get(Router);
        var snackBar = this.injector.get(MatSnackBar);
        console.log(err);

        if (err instanceof HttpErrorResponse) {
            var message = ErrorMessages.get(err.status);

            if (route.url.toLowerCase() !== '/login' && err.status === 401) {
                route.navigateByUrl('/login');
            }

            if (message.length > 0) {
                snackBar.open(message, "x", { duration: 5000, horizontalPosition: "center", verticalPosition: "bottom" });
            }
        }
    }
}

小吃店的位置在垂直底部和水平居中时

enter image description here

如果我在http拦截器中使用snackbar,它会正确显示

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
    constructor(private loginService: LoginService, private route: Router, private snackBar: MatSnackBar) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
        var url = this.route.url;
        var isAuthenticated = this.loginService.isAuthenticated();

        var authHeader = ``;
        if (isAuthenticated) {
            authHeader = `Bearer ${this.loginService.getToken()}`;
        }

        req = req.clone({
            setHeaders: {
                Authorization: authHeader,
                ApiKey: "aaa"
            }
        });

        return next.handle(req)
            .do((ev: HttpEvent<any>) => {
                if (ev instanceof HttpResponse) {

                }
            }, (err: any) => {
                if (err instanceof HttpErrorResponse) {
                    var message = ErrorMessages.get(err.status);

                    if (this.route.url.toLowerCase() !== '/login' && err.status === 401) {
                        this.route.navigateByUrl('/login');
                    }

                    if (message.length > 0) {
                        this.snackBar.open(message, "x", { duration: 5000, horizontalPosition: "center", verticalPosition: "bottom" });
                    }
                }
            });
    }
}

为什么?

1 个答案:

答案 0 :(得分:8)

我也遇到了这个问题,但使用HTTPInterceptor(或任何其他拦截器)

然而,我正在从一个组件(openFromComponent)打开SnackBar,这就是问题发生的时间(之前,我刚刚使用open)。

在区域内运行解决了我的问题。

您需要更新组件构造函数以包含NgZoneMatSnackBar服务:

constructor(
    private readonly msb: MatSnackBar,
    private readonly zone: NgZone
  ) { }

...然后启动:

private openErrorSnackBar(data: string[]) {
    this.zone.run(() => {
      this.msb.openFromComponent(ErrorSnackComponent, {
        data,
        horizontalPosition: 'end',
        duration: 5000
      });
    });
  }

我已将我的代码包装在一个便利函数中,该函数接受一个字符串数组(错误消息)以显示在Snackbar Component中,