Angular - finding an elegant solution for handling multiple HTTP requests

As a newcomer to Angular, I've been working on a project where I need to load various local .json files using http-requests. While my current approach works, I can't help but wonder if there's a more elegant solution.

Currently, I load the local files in this manner:

// Load data from file1
this.http.get("./assets/file1.json").subscribe(data => {
  this.file1 = data
})

// Load data from file2
this.http.get("./assets/file2.json").subscribe(data => {
 this.file2 = data
}) 
... (repeat for each file)

Each file's data needs to be stored in a separate variable (like this.file1, this.file2, etc.), and these http requests are made in the ngOnInit() method.

I've attempted using Observables, creating a function and subscribing to the data, but I'm unsure of how to apply it to multiple files.

this.loadFiles().subscribe(data => {
  this.file1 = data
});

public loadFiles(): Observable<any> {
    return this.http.get("./assets/file1.json");
}

I would greatly appreciate seeing some clean code examples for handling this task.

Answer №1

If you have a series of resource names in a sequential order (like file1, file2, file3...), you can organize them into an array of observables and utilize the combineLatest operator.

For instance, the code snippet below demonstrates fetching 100 JSON objects: visit StackBlitz

  ngOnInit() {
    combineLatest(this.addObservablesToArray()).subscribe((data) => {
      this.files.push(...data);
      console.log(this.files);
    });
  }

  addObservablesToArray(): Observable<any>[] {
    let observables = [];
    for (let i = 1; i <= 100; i++) {
      observables.push(
        this.http.get(`https://jsonplaceholder.typicode.com/todos/${i}`)
      );
    }
    return observables;
  }

Answer №2

Transform an array of file names into a series of http requests by mapping each filename to its corresponding request. When using forkJoin, all requests will be made simultaneously and once they have all finished, the results will be returned in the same order as the original filenames array.

const filenames = ['filename1', 'filename2', 'filename3'];

forkJoin(filenames.map(filename => this.http.get(`./assets/${filename}.json`))).subscribe(results => {
  // handle the results accordingly
});

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

experimenting with a TypeScript annotation

I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue ...

Efficiently Measuring the Visibility Area of DetailsList in Fluent UI

I am currently utilizing the DetalisList component alongside the ScrollablePane to ensure that the header remains fixed while allowing the rows to scroll. However, I have encountered a challenge as I need to manually specify the height of the scrollable co ...

Error NG0304: The element 'mat-select' is not recognized in the template of the 'LoginPage' component

After creating a basic app, I decided to incorporate Angular Material into my project. The app in question is an Ionic 6 / Angular 14 app, however, I encountered an error while attempting to implement mat-select: https://i.sstatic.net/Quc53.png To addres ...

Using TypeScript without specifying a specific argument in the any type

My function accesses local/session storage, but there is a condition that it can only be called if the window is defined. This function takes a generic args argument which I simplified to have a type of any[]. While using the useSessionStorage function, ...

The parameter type is not compatible with the argument type of 'SetStateAction'

I am new to next.js and typescript and I encountered a typescript error in vscode. Even though it does not impact the state variable, I am curious to understand why the error occurs and how to resolve it Error message: "Argument of type 'Movie | ...

Steps for exporting a package that has been imported

If in file1, the code is like this: import * as Things1 from "../things1" import * as Things2 from "../things2" export { Things1, Things2, } and in file2, it looks like this: import * as Distributor from "../file1" i ...

Struggling with a Nextjs Stripe issue? The expected signature for payload does not match any found signatures

Struggling to integrate data from Stripe check out events into my orders database, facing issues with finding the signature while testing the web hook. Check out route: app/api/webhooks/checkout/route.ts import Cors from "micro-cors"; import { h ...

How can I enable email and password login in @auth0/auth0-angular?

Auth0 SDK for Angular Single Page Applications - the documentation outlines two methods for logging in: loginWithPopup loginWithRedirect Is there a possibility to add another option for logging in with just an email and password? ...

What is the method for retrieving the index of an enum member in Typescript, rather than the member name?

Here is an example of how to work with enums in TypeScript: export enum Category { Action = 1, Option = 2, RealEstateFund = 3, FuturesContract = 4, ETFs = 5, BDRs = 6 } The following function can be used to retrieve the enum indexe ...

"Learn how to extract the image URL from the configuration file (config.json) within the assets folder, and then seamlessly display it within

In my Angular project, I have a configuration file located in the assets folder: { "brandConfig": "brand1", "brand1": {"urlPath": "http://192.168.168.60:8081/mantle-services", " ...

What is the best way to implement component lazy loading in Preact?

My objective is to create two bundles during the build process, one for the index.tsx file and another for the lazy.tsx file. I am confident that there are one or two options that I am overlooking. Check out the example project on GitHub - example project ...

What is the process for transferring data processed in Python to Node.js and then forwarding it to Angular?

I am a newcomer to Angular and I'm looking for a way to showcase JSON data from Python in my Angular app using Node.js. I have already utilized child processes to establish the connection between Python and Node.js, but I am facing a challenge on how ...

What is the best way to retrieve the filepath of a module that is lazily loaded

Here are the routes that I have set up: const routes: Routes = [ { path: 'path1', loadChildren: () => import('./child/child.module').then(r => r.ChildModule), }, { path: 'path2', loadChildren: () =& ...

Encountering a 401 Unauthorized error due to CORS origin issue when making a post request with HttpClient in Angular

Encountering an error when trying to upload data to my backend Firebase database. Here are the relevant code snippets: storeUsers(users: any[]){ return this.http.post('https://promise-90488.firebaseio.com/data.json', users); } appc ...

Issue with bundling project arises post upgrading node version from v6.10 to v10.x

My project uses webpack 2 and awesome-typescript-loader for bundling in nodejs. Recently, I upgraded my node version from 6.10 to 10.16. However, after bundling the project, I encountered a Runtime.ImportModuleError: Error: Cannot find module 'config ...

What is the process for removing a specific column (identified by its key value) from a JSON table using JavaScript and Typescript?

[{ "name": "employeeOne", "age": 22, "position": "UI", "city": "Chennai" }, { "name": "employeeTwo", "age": 23, "position": "UI", "city": "Bangalore" } ] If I remove the "Position" key and value from the JSON, the updated r ...

Accessing nested objects within an array using lodash in typescript

After analyzing the structure of my data, I found it to be in this format: {property: ["a","b"], value : "somevalue" , comparison : "somecomparison"} I am looking for a way to transform it into a nested object like so: { "properties": { "a": { ...

The p-dropdown component experiences issues with displaying the accurate label when the ngModel variable is an object

Currently, I am utilizing PrimeNG's p-dropdown component. Upon the initial page load, I am setting the ng-model, but the dropdown always displays the first element as the selected option. HTML <p-dropdown [options]="cities" [(ngModel)]="selectedC ...

Customize styles for a specific React component in a Typescript project using MaterialUI and JSS

I'm currently exploring how to customize the CSS, formatting, and theme for a specific React component in a Typescript/React/MaterialUI/JSS project. The code snippet below is an example of what I've tried so far, but it seems like the {classes.gr ...

How can we define and put into action a function in TypeScript that incorporates certain properties?

I have a vision of creating a message feature that can be invoked directly with overloading capabilities. I also wish to incorporate other function calls within this message feature, such as message.confirm(). Achieving this in TypeScript seems challenging ...