Search code examples
angularangular-standalone-components

How to use MatSnackBar in global error handler with standalone components?


I've created this error handler:

import { ErrorHandler, Injectable } from "@angular/core";
import { MatSnackBar } from "@angular/material/snack-bar";

Injectable({
    providedIn: 'root',
    
})
export class MyErrorHandler implements ErrorHandler {

    constructor(private _snackBar: MatSnackBar) { }

    openSnackBar(message: string, action: string) {
        this._snackBar.open(message, action);
    }

    handleError(error: any) {
        console.error(error);
        this.openSnackBar('An error occurred: ' + error.message??"No message", 'Close');
    }

}

and configured my app in main.ts to use it as the ErrorHandler:

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig)
  .catch((err) => console.error(err));


import { ApplicationConfig, ErrorHandler } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';  
import { MyErrorHandler } from './error-handling'; 

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),

    {
      provide: ErrorHandler,
      useClass: MyErrorHandler, 
    }
  ]
};

However, it gives error as it doesn't provide the "MatSnackBar" anywhere. It works correctly if i remove all references to MatSnackBar and I just log the error to console or something like that.

I have tried importing it in the @Injectable() decorator, but that didn't change behaviour.

How to use MatSnackBar or other dependencies in my ErrorHandler since i'm using standalone components and so i don't have a Module where i can import the MatSnackBarModule?


Solution

  • Solved by using "deps" in the app.config.ts file: import { MatSnackBar } from '@angular/material/snack-bar';

    {
          provide: ErrorHandler,
          useClass: MyErrorHandler,
          deps: [
            MatSnackBar
          ]
        }
    

    Important: "deps" doesn't work if you put it in the @Injectable() decorator, only here in the providers array.