I wanna use snack bar to show users the error, I want to know if I have to use error in my subscription method to use snack bar? is there any way to not use error in subscribe method and show error with snack bar? here's my http error-catching interceptor:
export const httpErrorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
return throwError(() => error);
})
);
};
and here is my subscribe method that subcribes and emit value from service:
login(): void {
let userInput: UserLogin = {
email: this.EmailCtrl.value,
password: this.PasswordCtrl.value
}
this.accountService.login(userInput).subscribe({
next: () => {
this.router.navigateByUrl('/');
this.snackBar.open('Login Successful', 'Close', {
duration: 3000
});
},
error: () => {
this.snackBar.open('Login Failed', 'Close', {
duration: 3000
});
}
});
}
is there a way to use snack bar for errors and don't use error in login method?
Your HTTP interceptor is a no-op. All it does is catch and rethrow the same exception without any side effects. You could remove it with no changes to your application.
To achieve your goal, you could define a global error handler using
ErrorHandler
.You can name this file
src/app/global-error-handler.ts
.Note that
NgZone
is used to fix a positioning issue withMatSnackBar
.You will also need to add a provider:
For standalone applications, you can add it in
src/app/app.config.ts
:Otherwise add it in the root module: