如何在Angular 2中访问json的元素

时间:2017-02-13 09:58:44

标签: json angular

当我做的时候

loadPeople(){

    this.myService.load().then(data => {
            this.people = data;
            alert(this.people);
        });
    }

它警告json:

 {
"status": "true",
"statusCode": 200,
"response": [{
    "user_id": "92",
    "firstname": "joy",
    "lastname": "Panchal",
    "email": "joy@gmail.com",
    "password": "7Y7+K0vZIVWPDUQH++Iu+/+tMZ",
    "user_type_id": "1"
}, {
    "user_id": "89",
    "firstname": "mark",
    "lastname": "haris",
    "email": "mark@gmail.com",
    "password": "4JICqnTkR8ysTI+nQQ+rpfAf7e",
    "user_type_id": "1"
}]

}

现在我正在尝试访问"响应"通过

loadPeople(){

this.myService.load().then(data => {
        this.people = data.response;
        alert(this.people);
    });
}

但它警告为" undefined"

任何人都可以告诉我失踪的地方吗?

2 个答案:

答案 0 :(得分:1)

你可以像这样访问。请试试。

`loadPeople(){
  this.myService.load().then(data => {
    this.people = JSON.parse(data.response);
    alert(this.people);
});

}`

答案 1 :(得分:0)

首先需要解析JSON:

this.myService.load().then(data => {
    let res = JSON.parse(data);
    this.people = res.response;
    alert(this.people);
  });
}