Search code examples
angularrxjsangular2-http

Angular2 http : Not able to Understad why I am getting user array with one piece of code and user object at a time with the another?


first :

 this.http.get('http://localhost:3000/users).
        map(users=>users.json())
        .subscribe(
        users=>{
        let user : User=users[0];
        console.log(user);
        }) 

second :

this.http.get('http://localhost:3000/users')
   .flatMap((resp:Response)=>resp.json())
   .filter((user : User)=>user.username==this.userName)
   .subscribe(
   (user : User)=>{
   console.log(user.username);
   })

I hope with subscribe I should be getting them each one at a time . Please let me know where i am wrong.


Solution

  • It is happening due to flatMap operator. A small example to illustrate this where we are getting one user object at a time :

    this.httpClient.get("http://localhost:3000/users")
    .flatMap(users=>{
    return Object.values(users)})
    .subscribe(
    user=>{
    this.users.push(user);
    });