我有一个从API调用接收到的JSON对象数组。
data = [{
"notificationId": null,
"notificationText": "xXXX YYY",
"notificationType": "typeA",
"fromId": 2,
"toId": 9,
"timestampCreated": {
"epochSecond": 1493898875,
"nano": 0
}},
{
"notificationId": null,
"notificationText": "YYYYYYY,
"notificationType": "typeB",
"fromId": 3,
"toId": 9,
"timestampCreated": {
"epochSecond": 1493898903,
"nano": 0
}}
]
我希望通过遍历此数组来获取各个Notification对象 我的通知界面如下所示
interface Notification {
notificationId: number;
notificationText : string;
notificationType : string;
fromId:number;
toId:number;
timestampCreated: Date ;
}
notif: Notification[] = [];
.
.
this.notif =data;
for(var i=0;i<this.notif.length ;i++){
console.log("notification text at "+this.notif[i].notificationText);
//this gives undefined
//and it loops through all the characters of the data
// not just twice
}
可以帮助一些人,我对angular2 / typescript世界很新。
答案 0 :(得分:0)
我正在回答这个问题,因为我发现了问题所在。在上面的代码片段中,对象数组实际上是JS对象的数组,而不是JSON对象。所以我需要解析对象才能将它们用作JSON。一个简单的JSON.parse(数据)修复了这个问题。