I am trying to implement HttpInterceptor in one of my Angular application to show a spinner on every request. The spinner shows beautifully. However, I also implemented a notificationService which utilizes SweetAlert to display notification modals based on the response from the server. I was able to display a Success modal but not Error modal. My codes are below:
INTERCEPTOR:
intercept(req: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> { this._spinnerService.requestStarted(); return next.handle(req).do( (event: HttpEvent<any>) => { if (event instanceof HttpResponse) { this._spinnerService.requestEnded(); } }, (err: any) => { if (err instanceof HttpErrorResponse) { this._spinnerService.requestEnded(); } } ); } LOGIN:
login() { this.spinnerSub = this.spinnerService.spinnerState.subscribe(state => { this.showSpinner = state; }); const user = { email: this.userEmail, password: this.userPw }; this.authService.authenticateUser(user).subscribe((data: ILoginResponse) => { this.spinnerSub = this.spinnerService.spinnerState.subscribe(state => { this.showSpinner = state; }); if (data.success) { this.notificationService.showSuccess(data.title, data.message) .then((result) => { console.log(result); this.router.navigate(['/user/dashboard']); }) .catch((reason) => { console.log('--> Alert dismissed: ', reason); }); } else { this.notificationService.showError(data.title, data.message) .then((result) => { console.log(result); }) .catch((reason) => { console.log('--> Error dismissed: ', reason); }); } }); } NOTIFICATION SERVICE:
showSuccess(type, message) { return swal({ title: 'Success', text: message, type: type }); } showError(type, message) { return swal({ title: 'Error', text: message, type: type }); } Any help/suggestion would be much appreciated. Thanks.
EDIT: I tried putting the NotificationService, specifically the showError() in the (err:any) block of the Interceptor. Well it works but I want to keep the NotificationService on specific components (like Login), not every requests.