0

I am using ToastrService to show notifications for server errors. But it does n't seems to be work. In the Ui if get request is not loading data to the tabular view due to a backed issue how to show the Toast message in the particular UI, component? Do I need to add something like timeout in that paricular component or app.component.ts file.

This is my httpInterceptor class.

@Injectable({
  providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
  constructor(public toasterService: ToastrService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     return next.handle(request).pipe(
            tap(evt => {
                if (evt instanceof HttpResponse) {
                    if (evt.body && evt.body.success) {
                        this.toasterService.success(evt.body.success.message, evt.body.success.title, {positionClass: 'toast-bottom-center'});
                    }
                }
            }),
            catchError((err: any) => {
                if (err instanceof HttpErrorResponse) {
                    try {
                        this.toasterService.error(err.error.message, err.error.title, {positionClass: 'toast-bottom-center'});
                    } catch (e) {
                        this.toasterService.error('An error occurred', '', {positionClass: 'toast-bottom-center'});
                    }
                    //log error
                }
                return of(err);
            }));
   }

}

This is my app.module.ts file

imports: [
  ToastrModule.forRoot(
            {positionClass: 'toast-bottom-center', timeOut: 5000,
                preventDuplicates: true,
                closeButton: true,
                progressBar: true,
                maxOpened: 1,
                autoDismiss: true,
                enableHtml: true},
        ),
],

providers: [
{provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true},
],

This is my messageService class.

export class MessageService {

  constructor(private toastr: ToastrService) { }
   showSuccessWithTimeout(message, title, timespan) {
        this.toastr.success(message, title , {
            timeOut :  timespan
        });
    }
    showError(message, title) {
        this.toastr.error(message, title, {
            enableHtml :  true
        });
    }

}

How can i show a Toast message to the user when the request time out or when backend server url is not found or for server errors like that?

Hans
  • 308
  • 7
  • 20

0 Answers0