Angular2,从REST调用中获取数据

时间:2016-12-21 17:05:07

标签: json rest angular

我正在通过id获取json文件中的数据,我获取了所有内容。 这里是JSON:

[
{ "id": "1", "name": "Carlos", "apellidos":"López", "edad":"30", "ciudad":"Hospitalet" },
{ "id": "2", "name": "Arantxa", "apellidos":"Pavia", "edad":"24", "ciudad":"Barcelona" },
{ "id": "3", "name": "Didac" , "apellidos":"Pedra", "edad":"muchos", "ciudad":"Cornellà" },
{ "id": "4", "name": "Daniel" , "apellidos":"Farnos", "edad":"nolose", "ciudad":"Barcelona" }
]

服务:

private usersUrl = 'app/users.json'; 
getUser(id: String): Observable<User>{
    let body = JSON.stringify(
      {
        "token": "test",
        "content": {
            "id": id
          }
        }
   );
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({
        headers: headers,
        body : body
      });

    return this.http.get(this.usersUrl, options)
        .map(res => res.json()).catch(this.handleError);
}

角度组件:

ngOnInit(){ 

    this.route.params.subscribe(params => {
        let id = +params['id'];
        this.apiService.getUser(id).subscribe( (res) => { console.log(res); } );            
    }) 

}

CONSOLE.LOG:

Array[4]0: Object1: Object2: Object3: Objectlength: 4__proto__: Array[0]

JSON不好吗?

感谢。

1 个答案:

答案 0 :(得分:0)

因为您没有按ID过滤结果。

.map(res => res.json())
.map(x > x.find(x => x.id == id) // filter by selected id
.catch(this.handleError);