2017-08-31 90 views
0

我應該保存多個JSON對象到類型的數組「聯繫」打字稿數組未定義

getContacts(){ 
    let self = this; 
    $.ajax({ 
     type: "GET", 
     url: "/chat/contacts/", 
     dataType:"json", 
     success: function(response){ 
      let obj = response; 
      let i = 1; 
      let contacts: Contact[] = []; 
      for (let key in obj) { 
       if (obj.hasOwnProperty(key)) { 
        let val = obj[key]; 
        contacts[i].id = val["id"]; //<-- contacts[i] is undefinded 
        contacts[i].partner = val["partnerId"]; 
        contacts[i].name = val["name"]; 
        contacts[i].type = val["type"]; 
        console.log(contacts[i]); 
       } 
      } 
     }, 
     error: function(jqXHR, textStatus, errorThrown){ 
      alert(errorThrown); 
     } 
    }); 
} 

在標記點,它說

接觸[i]是一個函數undefinded

我該如何初始化數組使其工作?

這裏是聯繫類:

class Contact extends BaseModel{ 
    static CCO_ID = "id"; 
    static CCO_PARTNER = "partner"; 
    static CCO_NAME = "name"; 
    static CCO_TYPE = "type"; 


    partner: Number; 
    name: String; 
    type: Number; 
} 
+0

使用contacts.push – N1gthm4r3

回答

3

您需要先定義contacts[i]是一個對象,然後使用它的屬性。

還有一件事,你從索引1開始,在Javascript數組的索引從0開始。請注意,如果這不是故意的。

let val = obj[key]; 
contacts[i] = new Contact(); // <-- Look here 
contacts[i].id = val["id"]; 
contacts[i].partner = val["partnerId"]; 
contacts[i].name = val["name"]; 
contacts[i].type = val["type"]; 
console.log(contacts[i]); 
+0

啊謝謝,工作! ^^ – Tim