Incorporating information into the output of an HTTP request with Angular 7

I have a list of asset IDs (assetIDs) and I need to fetch data using these IDs. Each HTTP request returns one or more datasets. My goal is to include the request ID in each dataset and then return the data.

The process of fetching and returning the data is working well, but I'm struggling with adding the assetID to the dataset.

When I try the code snippet below, I only receive the first dataset for each ID due to [0]. How can I iterate over all datasets?

getData(assetIds: Array<string>): Observable<any> {
  const data = assetIds.map(assetId => {
    // for each assetId
    const path = this.serverUrl + '?' + 'assetid=' + assetId;
    return this.httpClient.get(path).pipe(
      map((res: any[]) => {
        return {
          name: res[0].name,
          type: res[0].type,
          asset: assetId
        };
    }));
});

// return combined result of each assetId request
return forkJoin(data);
}

I also attempted the following approach, but didn't retrieve any data:

getData(assetIds: Array<string>): Observable<any> {
 const data = assetIds.map(assetId => {
  // for each assetId
  const path = this.serverUrl + '?' + 'assetid=' + assetId;
  return this.httpClient.get(path).pipe(
    map((res: any[]) => {
      const resultArray = [];
      res.forEach(element => {
        const row = {
          name: res[element].name,
          type: res[element].type,
          asset: assetId
        };
        resultArray.push(row);
      });
      return resultArray;
    }));
});
// return combined result of each assetId request
return forkJoin(data);

}

Answer №1

It appears that your second approach is on the right track. The issue may lie in the utilization of the rxjs operator known as forkJoin.

According to the RXJS documentation, this particular operator emits a value when:

When all observables complete, it emits the last emitted value from each.

You have two potential solutions: either switch out the forkJoin operator for zip,

which will emit values as an array after all observables have emitted their values,

or include the take(1) operator following the map within the pipe. This take operator will finalize the observable after emitting one value, allowing forkJoin to emit its values accordingly.

Answer №2

If you want to manipulate the result array further, you can use the map function. Here is an example:

const newData = assetIds.map(id => {
    // process each asset id
    const url = this.serverUrl + '?' + 'assetid=' + id;
    return this.httpClient.get(url).pipe(
      map((response: any[]) => response.map(item => {
        return {
          name: item.name,
          type: item.type,
          assetId: id
        }
      })));
  });

  // combine the results of all asset ids
  return forkJoin(newData);
}

Answer №3

Thank you for all your input. After trying various solutions, I realized that the issue stemmed from using "element" as an index in the array. By making some adjustments, the code now runs smoothly:

return this.httpClient.get(path)
  .pipe(
    map((datasets: AssetFilesTableItem[]) => {
      const result: AssetFilesTableItem[] = [];
      let i = 0;
      datasets.forEach(element => {
        const dataset: AssetFilesTableItem = {
          name: datasets[i].name,
          type: datasets[i].type,
          size: datasets[i].size,
          timestamp: datasets[i].timestamp,
          created: datasets[i].created,
          updated: datasets[i].updated,
          asset: assetId
        };
        result.push(dataset);
        i++;
      });

      return result;
    }));

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 method for transferring the value of a jQuery variable to a PHP variable without using AJAX?

Here is my JavaScript code: $('#affiliates_name').change(function(){ var id = $('#affiliates_name').val(); }); Below is the corresponding HTML: <select id="affiliates_name" style="display: none;" name="affiliates_name"> < ...

The for loop GET request is not successfully pushing data to MongoDB, leaving the database with no entries

My current challenge lies in transmitting data from my for loop to MongoDB. Upon executing the js file using node initCount.js in the console, no errors are returned and everything seems to be working correctly. However, upon checking my MongoDB backend, I ...

Exploring ways to send data to WebView in Flutter

How can I pass the location obtained in my Flutter app to a WebView for further processing within the opened site? var userLocation = Provider.of<UserLocation>(context); Here is my WebView setup: WebView( initialUrl: widget.url, javasc ...

Encountering a Typescript issue when linking a class component with the reducer

Within my class component that is linked to the redux rootReducer, I am encountering a TypeScript error specifically related to the mapPropsToState section. The error message reads: Property 'unit' does not exist on type 'DefaultRootState&ap ...

Attempting to transfer a username String from the client to the server using React and Typescript

I am working on a project where I need to send the username of a logged-in user from the Client to the Server as a string. Currently, I am able to successfully send an image file, but now I also need to send a string along with it. What I aim to do is repl ...

Obtain the identifier of a div within nested HTML components by utilizing jQuery

How do I retrieve the id of the first div with the class: post, which is "367", using jquery in the given HTML code: <div id="own-posts"> <span class="title">Me</span> <div class="posts_container"> <div class="post"& ...

Utilizing Vue Composables: Effectively Implementing Multiple Instances without State Sharing

In my VueJS application, I have a composable file that fetches information from an API and displays it in a table within two components simultaneously: // Here is a basic example of the composable implementation: export function useDatatable () { const t ...

Once the user logs out, they have the ability to navigate back using the back button. What steps can be taken to address this

route.ts const appRoutes: Routes = [ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'dashboard', canActiva ...

Exploring the canDeactivateFn syntax with Angular Documentation

As a first-year university student, I recently discovered that the canDeactivate() guard in Angular is deprecated, while the canDeactivateFn guard functions without any issues. Admittedly, navigating through official documentation is still new to me. From ...

Exploring ways to destructure the useContext hook with a null default value in your Typescript code

Initially, I set up a context with a null value and now I am trying to access it in another component. However, when I destructure it to retrieve the variables from the context, I encounter a TypeScript error: Property 'users' does not exist on ...

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

Is there a method to incorporate a click event for the confirm button in the ElMessageBox UI element?

When I try to remove data from the table, I need a warning message to appear in the center of the screen first. The delete function is already set up, but I'm struggling to figure out how to implement a confirm button click event with ElMessageBox. I ...

Live Node.js and Next.js apps experiencing issues with functioning websockets

Within my nodejs backend at https://backend.example.com, the following code resides in my server.js file: const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 7500 }, () => { console.log('S ...

Why aren't Dependencies like RxJS being installed from package.json in the Dockerfile?

As I try to containerize my application for deployment on GCP, I have encountered an issue during local testing. It seems that the rxjs module (and possibly others) listed in package.json is not being installed properly. When building my Dockerfile, I rec ...

Accessing my data on my personal server through firestore entails an extra step in the request process

If I were to set up Cloud Firestore on my personal server, wouldn't that create a "two-way trip" for accessing my data? What I find concerning is the fact that the client-side has to send a request to my server first, and then my server must reach ou ...

What is the best way to rekindle the d3 force simulation within React's StrictMode?

Creating an interactive force directed graph in React using D3 has been successful except for the dragging functionality not working in React StrictMode. The issue seems to be related to mounting and remounting components in ReactStrict mode 18, but pinpoi ...

Transferring UTM parameters to a different page via a button click

Is there a way to extract parameters from a URL after the "?" and add them to a button's href in order to redirect to another landing page? I want to transfer UTM parameters to another page using JavaScript within the button. Original Homepage: Dest ...

Having trouble getting jQuery JavaScript to work on Wordpress and feeling lost about how to implement no-conflict mode syntax

Trying to implement the code from this Codepen http://codepen.io/eternalminerals/pen/qdGvMo on my WordPress website at I understand that since WordPress is in no-conflict mode, I need to change $ to jQuery. I have made this adjustment and ensured that the ...

utilizing vueJS for global notifications

It may sound like a cliché question, but I still haven't grasped it. I have a primary component that is always loaded in the application. Let's refer to it as DefaultContainer.vue <template> <div class="app"> .... Notifi ...

Synchronous execution following a Node.js for loop integrated with callbacks

I'm facing a dilemma in my Nodejs application involving a for loop with callback functions. The loop iterates over an array, and for each value, an update operation is performed using a query, replacing the current value with the result of the query. ...