2

I need to inform the user if the POST, GET or PUT method was correctly performed. Is there a good way to do that.

For example POST method in component for sending data:

SendData() {
    this.srv.PostData(this.user).subscribe(
      data => {
        console.log('Success', data);
      },
      error => console.log('Error', error)
    );
  }

In Http service I have:

PostData(userdata: User) {
    return this.http.post<any>(this.url + this.postDataString, userdata);
  }

What I wish to have is: - get information that the POST or PUT is performed (how to get informed about 200 OK or other HTTP answer?) - get information that GET method is performed correctly (how to get informed about 404 Not Found or other HTTP error code?)

Thank you for any answer.

Regards

EDIT: What I added is:

import { Injectable } from '@angular/core';
import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpErrorResponse,
    HttpResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError, switchMap, filter, take, tap } from 'rxjs/operators';
//import 'rxjs/add/operator/do';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request).pipe(catchError(error => {

            if (error instanceof HttpErrorResponse && (error.status === 401)) {
                sessionStorage.setItem('accessToken', '');
            } else if (error instanceof HttpErrorResponse && (error.status === 500 )) {
               console.log('500 Internal Server Error', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 502 )) {
               console.log('502 Bad Gateway', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 503 )) {
               console.log('503 Service Unavailable', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 504 )) {
               console.log('504 Gateway Timeout', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 0 )) {
               console.log('503 Service Temporarily Unavailable', '', { timeOut: 5000 });
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 200 )) {
                console.log('200 OK', '', { timeOut: 5000 });
                 return throwError(error);
            } else  {
                return throwError(error);
            }
        }),
        tap((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse && event.status === 200) {
              console.log('SUCCESS - 200');
            }
          })
        );
    }
}

Now the question is, how can I invoke and give proper message regarding the method I am calling like: - GET data for User - Get data for Manager - etc. ?

So the question is how can I know which HTTP method and URL is in use right now?

Another Question: I need to send a user a snackbar or alert if anything is wrong. What is your recommendation for such function? Where should I call it?

1
  • Using intercepter you can handle http errors. Commented Dec 9, 2019 at 6:40

3 Answers 3

2

Create intercepter http.intercepter.ts

import { Injectable } from '@angular/core';
import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, switchMap, filter, take } from 'rxjs/operators';
import 'rxjs/add/operator/do';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(error => {
            if (error instanceof HttpErrorResponse && (error.status === 401)) {
            } else if (error instanceof HttpErrorResponse && (error.status === 500 )) {
               console.log('500 Internal Server Error');
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 502 )) {
               console.log('502 Bad Gateway');
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 503 )) {
               console.log('503 Service Unavailable');
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 504 )) {
               console.log('504 Gateway Timeout');
                return throwError(error);
            } else if (error instanceof HttpErrorResponse && (error.status === 0 )) {
               console.log('503 Service Temporarily Unavailable');
                return throwError(error);
            } else  {
                return throwError(error);
            }
        }));
    }
}

And inject it into app module like this.

import { HttpErrorInterceptor } from './core/http.intercepter';
providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }]
Sign up to request clarification or add additional context in comments.

4 Comments

And that is all?
It will work for all http request globally, when any request fail it will log corrosponding error.
That is what I needed.
I added the code with: ``` tap((event: HttpEvent<any>) => { if (event instanceof HttpResponse && event.status === 200) { //this.toastr.success("Object created."); console.log('SUKCES - 200'); } })``` Can I get to every 200 OK answer and inform the user regarding where it was intercepted?
0

You can use Interceptor,

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
       tap(event => {
         if (event instanceof HttpResponse) {
            console.log('succeed');
         }
        },err => {
           console.log(`Error code ${err.status}, body : ${err.error}`);
       }
    ))
  }

Comments

0

Use Interceptor for global

Here is example for you

 handleErrorM = (error: HttpErrorResponse) => {
    console.log('Handle on Component', error);

    if (error.status === 401) {
      this.showError = true;
      this.error = error.message;
      return Observable.of(error.message);

    }
    this.showError = true;
    this.error = error.message;
    return Observable.of(error.message);
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.