Search code examples
angularrxjsrxjs5rxjs6rxjs-pipeable-operators

How do I map a list of objects from an HTTP API to a list of strings?


I am trying to use the merge operator is given below. I want to put only 'Mr' before login but I am getting an error, your help is much appreciated, thank you

  let data=this.http.get('https://api.github.com/users');
  let output=data.pipe(map(data=>{'Mr, '+data.login}));
            output.subscribe(data=>{
  console.log(data);
})

Solution

  • As in my comment, the API returns an array of users. You therefore need to use the JavaScript array map operator inside the rxjs map to transform each individual user to the required string:

    let data = this.http.get<any[]>('https://api.github.com/users');
    let output = data.pipe(map(users => users.map(user => 'Mr, ' + user.login)));
    
    output.subscribe(data => console.log(data));
    

    Working example here: https://stackblitz.com/edit/so-map-github-users?file=src%2Fapp%2Fapp.component.ts