Managing HTTP requests with errors within a forEach loop in Angular 9

I am currently coding a script that iterates through an array to make HTTP requests.
Most of these requests are directed towards non-existent resources, but I do not have information on which ones specifically.
Here is the code snippet I am using:

    langs.forEach(lang => {
      this.http.get('assets/i18n/' + lang + '.json')
        .pipe(
          tap(data => console.log('server data:', data)),
          catchError(this.handleError),
        );
    });

Despite the code above, I am not seeing any output in the console, although I should be expecting some data structures.
What I do not want to see are error messages like:

GET http://localhost: 4205/assets/i18n/[...] 404 (Not Found)
, rather just the successful outcomes of the calls.
I am interested in finding out how to filter out errors and only retrieve valid data structures within a loop.
Thank you for your help.

UPDATE:

The method this.handleError is sourced from the Angular documentation:

private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message

    return throwError(
      'Something bad happened; please try again later.');
}

Answer №1

If you find yourself needing to execute multiple calls within a loop, my suggestion is to utilize the ForkJoin rxjs operator. Not only does it provide a more polished solution, but it also enhances performance by making all the calls simultaneously.

const requests = [];
languages.forEach(language => requests.push(this.http.get('assets/i18n/' + language + '.json')));
Observable.forkJoin(requests).pipe(catchError(this.handleError)).subscribe(results => {...});

Answer №2

To efficiently handle multiple HTTP requests in parallel, I suggest utilizing the forkJoin method. If there is a need to manage errors on individual requests while still capturing responses from others, error handling can be implemented for each request separately.

Here is an example implementation in the service.ts file:

getLanguages(): Observable<any[]> {
  const observables = langs.map(lang => {
    return this.http.get(`assets/i18n/${lang}.json`).pipe(
      catchError(() => of(null))
    );
  });

  return forkJoin(observables).pipe(
    // filtering out empty values from the array
    map(results => results.filter(x => !!x)),
  );
}

Once the service is set up as shown above, you can inject it into your component and subscribe to the getLanguages() function like this:

Here is how it can be done in the component.ts file:

ngOnInit() {
  this.service.getLanguages().subscribe(responses => {
    console.log(responses); // [ {}, {}, {}, ... ]
  });
}

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

What is the reason for the ngFor loop in Ionic 5 component not functioning properly?

I'm facing an issue with the *ngFor directive in one of my components. It's strange because it works fine in other components. Can anyone help me figure out what I might be doing wrong? @Component({ selector: 'app-age-picker', temp ...

The onRowSelect and onRowClick events are not being triggered on the Primeng table component in an Angular application

I am currently struggling to navigate to another component with the data selected when a row is clicked. I have been using p-table to accomplish this task. For some reason, neither onRowClick nor onRowSelection functions are being triggered. I even added ...

Revealing a single element in an Angular 6 application that is utilized by several modules

As I am in the process of breaking down a large module into smaller ones, I have encountered an issue that needs to be addressed. Here are the specifics: The Search component is currently being used across multiple components. Initially, it was declared i ...

The type 'string | AddressInfo' does not include a 'port' property and does not have a string index signature

When running in { port }, I encountered the following error: Type 'string | AddressInfo' has no property 'port' and no string index signature. How can I resolve this issue? Code: import * as express from 'express' const app ...

Determine the route parameter name based on the path string, for example, '/posts/:id'

My Route interface has a params object, and I'm looking to ensure type safety on that params object. For example: If we have a route config like this: { post: { path: 'posts/:id', } } navigate({ name: 'post', params: { wr ...

Library for Nodejs that specializes in generating and converting PDF/A files

Is there a library available that can convert/create a PDF/A file? I've been searching for solutions but the existing answers suggest using an external service or provide no response at all. I heard about libraries in other languages like ghostscriptP ...

Can angularJS unit tests be executed using the angular-cli command `ng test`?

In my current project, I am working on an AngularJS 1.6.X ES6 application and utilizing Mocha and Sinon for writing and running unit tests. Recently, I began the process of hybridizing/upgrading this application using ngUpgrade to incorporate new componen ...

Execute environment validation on server during `next build` command

I have a src/config/server/ts file that contains the following code: 'use server'; import zod from 'zod'; if (typeof window !== 'undefined') { throw new Error('env should not be imported on the frontend!'); } co ...

Tips for accessing the value stored within the parent element

As someone who is new to the world of javascript and typescript, I am currently working on an ionic application that involves fetching a list of values from a database. These values are then stored in an array, which is used to dynamically create ion-items ...

Calling a function within another function is not allowed in Typescript

Essentially, I have an Angular Web Page that uploads a file to the server via a POST request, which is then received by my NodeJS app. The issue arises when attempting to retrieve the file path in subirArchivo() and pass it to a function called InsertaPer ...

Production is experiencing a hiccup, however, the site is still up and running. There seems to be

Having an error in production that I can't seem to replicate on my local machine. The error message reads: src/controllers/userController.ts(2,29): error TS2307: Cannot find module '../services/UserService' or its corresponding type declarat ...

Steps for sending HTTPS requests from Angular 6 to Node.js

In my MEAN stack app, I have Angular built in the public folder of Express to run the server on the same port. I also have a certificate from Cloudflare added to Node.js for HTTPS server, and my server is running on Nginx. I have opened port 443 on EC2, an ...

What is the importance of having typings when using TypeScript?

I recently came across a post on setting up Material-UI for React with Typescript on Stack Overflow: How to setup Material-UI for React with Typescript? As someone who is brand new to typescript, I initially assumed that typescript was simply a superset o ...

Unit testing in Angular 2: Triggering hover events

In my setup, I have a template for a specific component (MyCmp) that looks like this <template ngFor let-r [ngForOf]="range" let-index="index"> <span>{{ index < 5 ? 'Y' : 'N' }}, {{r.data}}</span> <i (mousee ...

Unleash the potential of a never-ending expansion for grid cells on Canvas

ts: templateStyle = { display: 'grid', 'grid-template-columns': 'calc(25%-10px) calc(25%-10px) calc(25%-10px) calc(25%-10px)', 'grid-template-rows': '150px auto auto', 'grid-gap ...

A more efficient approach to specifying types for the 'navigation' object in React Native's Stack Navigator

Struggling with modularizing prop types in React Navigation, particularly when using TypeScript. The Typescript section of the React Navigation documentation suggests defining types for each screen props in this manner: //types.ts export type RootStackPara ...

What is the best way to set up the parser and plugins using ESLint's updated flat configuration?

How can ESLint be configured using the new "flat config" system (specifically with the eslint.config.js file) to work seamlessly with both @typescript-eslint/eslint-plugin and /parser? I have been struggling to make ESLint's new configuration system ...

Showcasing a recently incorporated mat-card

I have a collection of mat-cards that are being displayed using data received through an observable called cars$. Each time a new car object is emitted by this observable, a new mat-card appears automatically. Is there a way to make the newly added mat-c ...

Adaptively linking to the property of a deeply nested object

Attempting to bind to a property of a nested object using [(ngModel)], but facing the challenge that the path to the property is dynamically set. Consider the following three classes: class A { p1: C constructor() { p1 = new C("A") } } class B { p2: ...

Encountering a bug in Angular 10 while attempting to assign a value from

I am having trouble updating the role of a user. In my database, I have a user table and a role table with a ManyToMany relation. I can retrieve all the values and even the correct selected value, but I am encountering issues when trying to update it. Her ...