Search code examples
javascriptangularhttpangular7

Join http results


I need to join the results of this two http requests:

this.http.get("https://jsonplaceholder.typicode.com/todos"); this.http.get("https://jsonplaceholder.typicode.com/users");

by his columns todo.userId = user.id

Which is the best way to accomplish this?

I'm using angular 7

I know this is a question asked in so many places, but I didn't found one that fits my needs.


Solution

  • Assuming you are literally trying to join all of the todo items up with their users by the user id, Array.map will do the job.

    After you get both data sets, just use Array.map to cycle through all of the Users and grab their todos

    // This function is just to fake the `this.http.get`
    function httpGet(url) {
      return new Promise( async (resolve, reject) => {
        const result = await fetch(url);
        const data = await result.json();
        resolve(data);
      });
    }
    
    // Create an array of promises to resolve your endpoints at once
    
    const promises = [
      httpGet('https://jsonplaceholder.typicode.com/todos'),
      httpGet('https://jsonplaceholder.typicode.com/users')
    ];
    
    // Wait for both promises to finish, then use Array.map to 'join' them
    Promise.all(promises).then( results => {
      const todos = results[0];
      const users = results[1];
    
    
      // This is the notable part
      const result = users.map( u => {
        u.todos = todos.filter( t => t.userId === u.id );
        return u;
      });
      // End of notable part
    
      console.log(result);
    });