Dealing with HTTP response errors in an Angular application

Below is the content of my data.json file:

[
    {"value":1},
    {"value":2},
    {"value":3},
    {"value":3}
]

& When using Http to retrieve this data, it works fine. However, if the server is turned off, an error is thrown. I want to display a custom message to the user instead of showing the error. The function below is responsible for fetching the data.

 data: any;

  getData() {
    this.http.get('http://localhost/php/data.json').subscribe((res) => {
      this.data = res;
      console.log(this.data);
    })
  }

  ngOnInit() {
    this.getData();
  }

Answer №1

  loadData() {
    this.http.get('http://localhost/php/data.json').subscribe((res) => {
      this.data = res;
      console.log(this.data);
    },(err:HttpErrorResponse)=>{handle any errors here});

When using subscribe, you can provide an error handling callback as the second argument. For more information on handling HTTP errors in Angular, please refer to the API documentation located at

https://angular.io/api/common/http/HttpErrorResponse

Answer №2

Another option is to utilize the catchError operator that comes with rxjs library

import {catchError} from 'rxjs/operators'

this.http.get('http://localhost/php/data.json')
    .pipe ( 
       catchError((error) => // deal with the error here; )
     )
    .subscribe((res) => {
      this.data = res;
      console.log(this.data);
    })

Answer №3

To capture a specific instance, follow these steps:

getData() {
    this.http.get('http://localhost/php/data.json').subscribe((res) => {
      this.data = res;
      console.log(this.data);
    }, (err:HttpErrorResponse) => {
        consdole.log(err)
     })
  }

Using an interceptor is recommended for centralized error handling:

Create a file named http-interceptor.ts:

import { Injectable, Injector } from '@angular/core';
import {
    HttpEvent,
    HttpHeaders,
    HttpInterceptor,
    HttpResponse,
    HttpErrorResponse,
    HttpHandler,
    HttpRequest
} from '@angular/common/http';



import { Observable } from 'rxjs/Observable';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(
        private appService: AppService) {

    }

    /**
     * 
     * @param req - parameter to handle http request
     * @param next - parameter for http handler
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        /**
         * Handle newly created request with updated header (if given)
         */
        return next.handle(req).do((event: HttpEvent<any>) => {
            /**
             * Sucessfull Http Response Time.
             */
            if (event instanceof HttpResponse) {
                const elapsed = Date.now() - started;
            }

        }, (err: any) => {
            /**
             * redirect to the error_handler route according to error status or error_code
             * or show a modal
             */
            if (err instanceof HttpErrorResponse) {
                console.log(err);
            }
        });
    }

}

In your module.ts file:

Add the following to providers:

{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true,
}
]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it best practice to utilize multiple Angular routing files?

Currently, I am working on a personal project to enhance my learning experience. Today, I encountered a question while expanding my codebase by creating additional modules. My goal is to prevent app.module from becoming overwhelmed with component imports, ...

Angularfire2 combined with Bootstrap Modal will enhance the user experience of

Hello everyone, I am currently facing an issue while trying to integrate Bootstrap modal with AngularFire2 in Angular. The problem lies in the fact that the data retrieved from the database is not being recognized. <button *ngFor="let utilfaq of (uti ...

Why use rxjs observables if they don't respond to updates?

I have an array of items that I turn into an observable using the of function. I create the observable before populating the array. However, when the array is finally populated, the callback provided to subscribe does not execute. As far as I know, th ...

Learn how to incorporate a 'Select All' feature as the primary choice in DevExtreme SelectBox with Angular 15 through Html coding

We are looking to replicate the following basic HTML select in Angular 15 using a dropdown control from DevExpress known as dx-select-box <select ng-model="selectedVal" ng-change="selectedValueChanged()"> <option value=&q ...

What is the best data type in Asp Net Core C# for capturing Angular's blob object?

I am working with an image BLOB object in Angular 5 and need to send it to the backend via an API. In previous versions of Asp.Net, there was 'HttpBaseType' for this purpose, but it is not available in Asp.Net core. Which data type should be use ...

Tips for incorporating asynchronous validation into a reactive form

Trying to implement asynchronous validation in an angular 13 app following the official guide Below is the implementation: check-current-password.validator.ts @Injectable({ providedIn: 'root' }) export class CheckCurrentPasswordValidator implem ...

checkbox causing the button to appear empty

Due to the inability of a ngIf and ngFor to coexist, I added an ng-container to facilitate the loop. However, after making this change, nothing seems to be working as expected without any clear reason. Below is the code snippet that is causing trouble: Vi ...

Retrieve a formatted item from a JSON document

Within my Next.js project, I have implemented a method for loading translations and passing them into the component. Here is an example: import "server-only"; import i18nConfig from "../../i18n-config"; const dictionaries = { en: () ...

Retrieving the active slide's property in MongoDB using Ionic React

I'm attempting to display a collection field based on the ObjectId linked to another collection in MongoDB. I have three collections: Users: { "_id" : "115ds1f4sd55fe1e51fds5f4", "name" : "Sam", &qu ...

Running the "ng -v" command results in an issue with rxjs being displayed

Upon running the following commands to update my command line interface: npm upgrade -g @angular/cli npm upgrade @angular/cli Running ng -v returns the following information: Angular CLI: 6.0.7 Node: 8.11.2 OS: darwin x64 Angular: ... Package ...

What is the best way to initialize a component only when its tag is set to *ngIf=true?

Update: After receiving a very helpful answer from Günter Zöchbauer that resolved my issue, I still have a lingering question about the correct approach for achieving the desired result. The context is provided below. With my custom tag on the parent ...

Versatile functions and unique index classifications

I need help creating a versatile function that takes a type argument "T" representing an object. It should use keyof T to determine the first argument named "property". However, I am struggling with defining the type of the second argument, called "value", ...

Angular 2 and Bootstrap 4 combine to create a stunning side-by-side image display on your

I can't figure out how to display the images next to each otherhttps://i.sstatic.net/yMGgH.png <div class="row"> <div class="col"> <div *ngFor="let ir of imagesSource"> <div class="row"& ...

What is the best way to hide the back arrow in Cordova UWP for Ionic 4?

I am currently developing a Windows 10 (UWP) application using Ionic 4 (Angular). I want to remove the back arrow from the interface: Example of back arrow I have attempted various solutions, such as implementing in the app.component constructor with in ...

Using ADAL with ASP.NET MVC and Angular for Seamless Login Experience

Currently, we have an ASP.NET MVC application in place but are looking to incorporate Angular for new frontend functions and gradually transition the entire frontend to Angular. However, at this stage, we are facing a challenge where user logins are only b ...

What are the steps to troubleshoot a Node Package Manager library in Visual Studio Code?

I have created a Typescript library that I plan to use in various NodeJS projects. The source code is included in the NPM package, so when I install it in my projects, the source also gets added to the node_modules folder. Now, during debugging, I want to ...

Determining the TypeScript function's return type depending on the type of the argument

I am facing a scenario where I have two distinct interfaces: A and B, both sharing a common property. Additionally, I possess two arrays containing items typed with either one of these interfaces. My objective is to create a function that can map these arr ...

Utilizing nested observables for advanced data handling

Consider the following method: public login(data:any): Observable<any> { this.http.get('https://api.myapp.com/csrf-cookie').subscribe(() => { return this.http.post('https://api.myapp.com/login', data); }); } I want to ...

Removing data based on various criteria in Prisma

While I understand that the where clause in Prisma requires a unique input for its delete operation, I have utilized the @@unique function to ensure that multiple conditions need to be columns together and must be unique. However, I am struggling with how ...

What is the correct version compatibility matrix for Expo, NPM, Node, React Native, and TypeScript?

Currently, I am in the process of setting up React Native with TypeScript. Here are the steps I followed: npx react-native init MyApp --template react-native-template-typescript I made sure to install TypeScript as well: npm install -g typescript ' ...