Currently, I am working on setting up a new interceptor within an Angular 16 project. However, when attempting to inject MatSnackBar into the project, I encounter the following error message:
NullInjectorError: NullInjectorError: No provider for MatSnackBar!
My goal is to display a snackbar notification whenever the API returns an error code. To simplify this process, I created a snackbar service. Unfortunately, both using the service and MatSnackBar directly result in the same error.
Below is a snippet of the interceptor code:
export const requestErrorsInterceptor = (
req: HttpRequest<unknown>,
next: HttpHandlerFn
): Observable<HttpEvent<unknown>> => {
try {
let matsnack = inject(MatSnackBar);
//let snackBarService = inject(SnackBarService);
} catch (error) {
console.log(error);
}
return next(req).pipe(
map((event: HttpEvent<any>) => {
return event;
}),
catchError((err: any) => {
if (err instanceof HttpErrorResponse) {
let message = '';
if (err.status === 0) {
message = 'connection-issues-message';
}
return throwError(() => err);
}
})
);
};
Here is my provider setup:
import {
HTTP_INTERCEPTORS,
provideHttpClient,
withInterceptors,
} from '@angular/common/http';
import { EnvironmentProviders, Provider } from '@angular/core';
import { requestErrorsInterceptor } from './interceptors/request-errors.interceptor';
import { requestInterceptor } from './interceptors/request.interceptor';
export const provideApplication = (): Array<Provider | EnvironmentProviders> => {
return [
provideHttpClient(
withInterceptors([requestErrorsInterceptor])
),
{
provide: HTTP_INTERCEPTORS,
useValue: () => {},
multi: true,
},
];
};