从 angular 5 中的数组中获取值

get values from array in angular 5

我想从数组中检索值我的代码是这样的

this.RoleServiceService.getRoleById(this.id).subscribe(data => {
  this.roleData.push(data['data']);
  console.log(this.roleData);
})

但我得到的数组是这样的

我已经试过了 role=roleData[0]; 但是给出了 undefined 你能帮我解决这个问题吗

    []
0
:
Array(4)
0
:
{id: 5, name: "edit_page", guard_name: "api", created_at: "2018-03-30 10:09:38", updated_at: "2018-03-30 10:09:38", …}
1
:
{id: 6, name: "create_page", guard_name: "api", created_at: "2018-03-30 10:09:38", updated_at: "2018-03-30 10:09:38", …}
2
:
{id: 7, name: "create_post", guard_name: "api", created_at: "2018-04-06 11:11:40", updated_at: "2018-04-06 11:11:40", …}
3
:
{id: 8, name: "view_post", guard_name: "api", created_at: "2018-04-06 11:11:40", updated_at: "2018-04-06 11:11:40", …}
length
:
4

你必须接受,this.roleData = data['data']

由于 data['data'] returns 和 array,您将该数组推到第一个 index;

是错误的
this.roleData = [];

this.RoleServiceService.getRoleById(this.id).subscribe(data => {
  this.roleData = data['data'];
  console.log(data['data']);
  console.log(this.roleData);
})

如果你想 append the data 你也可以使用 for loop

附加数据:

this.RoleServiceService.getRoleById(this.id).subscribe(data => {
  data['data'].forEach(element => {
    this.roleData.push(element)
 });
  console.log(data['data']);
  console.log(this.roleData);
})