2017-11-11 102 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

是的,但在控制台 –