angulartoastr

Where do I put my toastr service in angular?


I want have a standard api response like following.

For success response:

 {
    "version": "1.0",
    "statusCode": 200,
    "result": {data....}
 }

For error response:

 {
    "version": "1.0",
    "statusCode": 500, (this may be 401, 404,403,...)
    "errorMessage": {message....}
 }

My service like following:

export class MyService {

  constructor(private http: HttpClient) { }

  getData(): Observable<any[]> {
    return this.http.get<any[]>(`http://localhost/data`).pipe(map((response: any) => {
      return response;
    }))
  }
}

I need to show popups if response has errors using toastr. So where I use my toastr service for best solution?

I do not want to repeat myself.


Solution

  • If you have a lot of http requests, You can centralize it by using an http interceptor , try something like this:

    @Injectable()
    export class HttpInterceptor implements HttpInterceptor {
    constructor(public toasterService: ToastrService) {}
    
    intercept(
        req: HttpRequest<any>,
        next: HttpHandler
      ): Observable<HttpEvent<any>> {
    
        return next.handle(req).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);
            }));
      }
    }