Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snackbar position wrong when use errorhandler in angular 5 and material

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

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

enter image description here

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

Why ?

like image 664
Snake Eyes Avatar asked Apr 30 '18 13:04

Snake Eyes


1 Answers

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

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).

Running from within a zone fixed my problem.

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

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

...and then launch:

private openErrorSnackBar(messages: string[]) {

    this.zone.run(() => {

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

    });

  }

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

like image 99
Jack Avatar answered Oct 10 '22 18:10

Jack