Angular 2 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?

首先:

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

秒:

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);
   })

我希望通过订阅,我应该一次订阅一个。请让我知道我哪里错了。

问题出在您请求的 url 中,第一个通过 username 因此您的查询将 return 单个用户,在第二个 url您不是从后端过滤结果,而是通过 Observable 上的 filter 方法过滤,因此它将 return 来自后端的所有用户作为数组然后 select 只有一个符合您的过滤器。

您可以使用如下所示的 for-of 循环访问每个用户的数据:

this.http.get('http://localhost:3000/users')
   .flatMap((resp:Response)=>resp.json())
   .subscribe(
   (users : User[])=> {
        for (let user of users) {
            console.log(user.username); 
        }
   })

或者您可以删除第二个查询的 filter 部分并在 subscribe 正文中手动过滤。

这是由于 flatMap 运算符而发生的。一个小例子来说明这一点,我们一次获得一个用户对象:

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