2017-11-11 101 views
0

我想在JSON響應對象數組環在JSON數組使用打字稿

JSON響應循環:

{ 
"$id": "1", 
"Council_ID": 116, 
"number": "67", 
"subjects": [ 
    { 
     "$id": "2", 
     "subjectCode": "67", 
     "type": 4, 
    }, 
    { 
     "$id": "3", 
     "subjectCode": "67", 
     "type": 4, 
    } 
    ] 
} 

model.component.ts:

this.dataStorageService.storeSubjects(newSubject, this.meetingID) 
     .subscribe(
     response => { 
      this.dataStorageService.getCouncilId(this.meetingID).subscribe(response => { 
       this.subjectsWithID = response.json(); 
       this.sublength = this.subjectsWithID.subjects.length; 
       console.log(this.sublength); 
       for(let i = 0 ; i <= this.sublength; i++){ 
        this.typee = this.subjectsWithID.subjects[i].type; 
        this.dataStorageService.getSubjectTypeId(this.typee).subscribe(response =>{ 
         this.namesOfSub = Array.of(response.json()); 
         console.log(this.namesOfSub) 
        }); 
       } 
       // console.log(this.typee, 'bla bla'); 
      }); 
      this.addSubjectForm.reset(); 
      this.router.navigate(['/model']); 
      return true; 

這給我的錯誤: - 屬性'主題'在類型'any []'上不存在。有任何建議擺脫這個錯誤?

+0

告訴你subjectsWithID – Sajeetharan

+0

您使用的HttpClient如何申報? –

+0

@Sajeetharan的學科無法讓我看看這個Json迴應我張貼了 –

回答

1

確定使用httpClient,你不能獲得屬性this.subjectsWithID.subjects,但usinh http是可能的,這是因爲httpClinet在解析結果時它確實知道你的對象的份額,你必須給出一個鍵入您的結果,或者你可以像這種訪問你的財產:

this.subjectsWithID['subjects'] 

,或者你可以指定類型使用接口:

return this.http.get<myObject>(...url) 

interface Sidebar { 
    id: number; 
    Council_ID: number, 
    number: number, 
    subjects: [... 
    } 
+0

,但現在給我錯誤無法讀取控制檯中未定義的屬性「類型」? –

+0

當使用此:this.subjectsWithID ['臣民']? –

+0

是的,但在控制檯 –