Search code examples
angularapihttpionic-frameworkconnection

Angular Status 0 if Api offline


I am trying to show a message if the API is offline on my angular app.

At my HttpInterceptor, I have:

return next.handle(request).pipe(
    tap(
        event => {
            if (event instanceof HttpResponse) {
                // console.log('all looks good');
                // http response status code
                //console.log(event.status);
            }
        },
        error => {
            if (error.status == 0) {
                error.message = 'API is Offline.', 'error'
            }
            console.error(error.status);
            console.error(error.message);
        }
    )
);

So i want to intercept the error to return the message for my Component or Service, when he fails.

My component calling a service:

this._service.new()
    .subscribe(
        res => {
        },
        err => {
          this._messageHelperService.showToast(err.error.message, 'error');
        }
    );

Can someone helps me ? thanks.


Solution

  • Try Throwing the error using throwError in the HttpInterceptor.

    Example:

        tap(
            event => {
                if (event instanceof HttpResponse) {
                    // console.log('all looks good');
                    // http response status code
                    //console.log(event.status);
                }
            },
            error => {
                if (error.status === 0) {
                    return throwError('API is Offline., error')
                   // error.message = 'API is Offline.', 'error'
                }
                console.error(error.status);
                console.error(error.message);
            }
        )
    );
    

    And then you can access the error in your component in the same way you are using.