[英]How to get data from api response in Angular
I'm using Angular 4, I've made a call to an api which returns an array of objects. 我正在使用Angular 4,我已经调用了一个api,它返回了一个对象数组。
Then I tried to get specific data by referencing res.name
but for some reason I get undefined so I tried res[0]name
and res['name']
which returns only the first name but I want all the names from the array. 然后,我尝试通过引用res.name
来获取特定数据,但是由于某种原因,我不确定了,所以尝试了res[0]name
和res['name']
,该方法仅返回名字,但我希望从数组中获取所有名称。
Here is my array: 这是我的数组:
[{"name":"joey","surname":"jackson","email":"joey@gmail.com","phone":"0815342119"},
{"name":"Tim","surname":"Muller","email":"tim@gmail.com","phone":""},
{"name":"Kim","surname":"Van Dam","email":"kim@gmail.com","phone":""},
{"name":"Lyn","surname":"Davids","email":"lyn@gmail.com","phone":""}]
Try using forEach
to iterate over all elements of an array: 尝试使用forEach
遍历数组的所有元素:
let res = [ {"name":"joey","surname":"jackson","email":"joey@gmail.com","phone":"0815342119"},{"name":"Tim","surname":"Muller","email":"tim@gmail.com","phone":""},{"name":"Kim","surname":"Van Dam","email":"kim@gmail.com","phone":""},{"name":"Lyn","surname":"Davids","email":"lyn@gmail.com","phone":"08343435"} ]; res.forEach( (el) => { console.log(el.name); })
You should use the dot operator when you are accessing property 访问属性时应使用点运算符
it should be as, 应该是这样
res[0].name;
or 要么
res[0]['name'];
Assuming let people = [your array of objects]
假设let people = [your array of objects]
In newer JS: 在较新的JS中:
for (person of people) {
console.log(person.name)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.