简体   繁体   English

Angular2,从REST调用中获取数据

[英]Angular2, get data from REST call

I'm triyng to get data from json file by a id, by I'm getting all the content. 我正在通过ID获取json文件中的数据,因为我获取了所有内容。 Here the 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" }
]

Service: 服务:

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

Angular Component: 角分量:

ngOnInit(){ 

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

}

Console.log: CONSOLE.LOG:

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

Is the JSON bad? JSON不好吗?

Thanks. 谢谢。

Because you didn't filter the result by id. 因为您没有按ID过滤结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM