在角度 5 和材料中使用 errorhandler 时,Snackbar 位置错误 [英] Snackbar position wrong when use errorhandler in angular 5 and material

查看:22
本文介绍了在角度 5 和材料中使用 errorhandler 时,Snackbar 位置错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have custom global error handler

@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" });
            }
        }
    }
}

snackbar 的位置不是在垂直底部和水平居中.

The position of snackbar is not at vertically bottom and horizontally centered.

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

If I use snackbar in http interceptor, it is displayed correctly

@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" });
                    }
                }
            });
    }
}

为什么?

推荐答案

我也有这个问题但是没有使用 HTTPInterceptor(或任何其他拦截器).

I had this problem too but was not using HTTPInterceptor (or any other interceptors).

然而,我正在使用 SnackBar 创建和分发带有自定义组件的 code>openFromComponent - 这是出现问题的时间(以前,我使用的是 open).

I was however creating and dispatching the SnackBar with a custom component using openFromComponent - this is when the problem occurred (previously, I was using open).

在一个区域内运行解决了我的问题.

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

You'll need to update the component constructor to include NgZone and MatSnackBar services:

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

...然后启动:

private openErrorSnackBar(messages: string[]) {

    this.zone.run(() => {

      this.msb.openFromComponent(ErrorSnackComponent, {
        data: messages,
        horizontalPosition: 'end',
        duration: 5000,
      });

    });

  }

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

I've wrapped my code in a convenience function which accepts an array of strings (error messages) to display within the Snackbar Component,

这篇关于在角度 5 和材料中使用 errorhandler 时,Snackbar 位置错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆