I'm trying to display the response I get from my backend. So, I created a service to show snackbars, then I'd like to implement it in my interceptor. I'm using stand alone components, so I need to keep using functional component because of the provideHttpClient(withInterceptors...))
Here is my interceptor
import { SnackbarService } from '../services/snackbar.service';
import { inject } from '@angular/core';
import { HttpInterceptorFn } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
export const errorHandlerInterceptor: HttpInterceptorFn = (req, next) => {
const snackbarService: SnackbarService = inject(SnackbarService);
return next(req).pipe(
catchError((error) => {
console.log(snackbarService);
snackbarService.openErrorSnackbar('Error found: ' + error.error);
return [];
})
);
};
here is my service
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
@Injectable({
providedIn: 'root',
})
export class SnackbarService {
constructor(private snackBar: MatSnackBar) {}
public openErrorSnackbar(message: string): void {
this.snackBar.open(message, 'Dismiss', {
duration: 5000,
panelClass: ['error-snackbar'],
});
}
}
my app.config
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { routes } from './app.routes';
import { errorHandlerInterceptor } from './core/interceptors/error.interceptor';
import { provideAnimations } from '@angular/platform-browser/animations';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideAnimations(),
provideHttpClient(withInterceptors([errorHandlerInterceptor])),
]
};
and my app.module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http'
@NgModule({
declarations: [],
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forRoot([]),
],
bootstrap: [],
providers: [HttpClientModule, ]
})
export class AppModule {}
So I tried to console log my interceptor, this works. It's the snackbar stuff that does not. I've tried
- change my functional service by a class
- add providers in the .module or .config
- display in one of my standalone components (not using the service to check if I can at least display a snackbar)
Here is a working example to demonstate it works, I found few issues.
BrowserModule,HttpClientModule,RouterModule.forRoot([])we can remove them!We can configure it like below
please focus on the providers array above, the rest might be irrelevant!
Hope this working example solves your issue!
stackblitz