【发布时间】:2018-08-02 14:48:11
【问题描述】:
我有以下接口用作 JSON 文件的类型:
export interface IIndustrySectors {
IndustrySector: string;
isSelected: string;
dataSubjectCategories:string[];
dataTypeCategories:string[];
SubIndustries:[{
IndustrySector: string;
isSelected: string;
dataSubjectCategories:string[];
dataTypeCategories:string[];
SubIndustries:[{}]
}]
}
还有两个服务:
// Read all the Data from the JSON file
getMainIndustrySectors(): Observable<IIndustrySectors[]> {
return this.http.get<IIndustrySectors[]>(this.industrySectorsURL).pipe(
tap(((data) => console.log('All: ' + data) )),
catchError(this.handleError)
);
}
//Get Specific object
getBySector(sector): Observable<IIndustrySectors| undefined> {
return this.getMainIndustrySectors().pipe(
map((products: IIndustrySectors[]) => products.find(p => p.IndustrySector === sector)));
}
这是 JSON 文件的一部分
[
{
"IndustrySector":"Accommodation and Food Service Activities",
"isSelected": "false",
"dataSubjectCategories":["DS.Employees","DS.Collaborators"],
"dataTypeCategories":"Personal Data",
"SubIndustries": [
{
"IndustrySector":"Food and Beverage Service Activities",
"isSelected": "false",
"dataSubjectCategories":[],
"dataTypeCategories":[],
"SubIndustries":[]
},
{
"IndustrySector":"Accommodation",
"isSelected": "false",
"dataSubjectCategories":["DS.Minor","DS.Parent","DS.Legal Person","DS.Natural Person","DS.Disable"],
"dataTypeCategories":[],
"SubIndustries":[]
}
]
}
]
问题是当我通过以下代码调用服务“getBySector”时:
this.readjsonService.getBySector(sector).subscribe(response=>{
if(response.dataSubjectCategories.length>0)
{
for(i=0; i<response.dataSubjectCategories.length;i++ ){
this.DSofSectores.push(response.dataSubjectCategories[i])
}
}
})
它抛出一个错误:
TypeError: 无法读取未定义的属性“dataSubjectCategories”
不过,它会打印值。
为什么会这样?
做什么是基于扇区,我得到“响应”与它相关的其他数据并填充一个绑定到下拉列表的字符串类型的数组。它工作正常,但下图显示了选择子扇区后发生的情况:
请帮助我,我是新手,我对此感到非常厌烦:(( 谢谢。
编辑: 当我说
if (response == undefined) {
throw new Error("sector not found");
}
else { .....
它通过了条件,意味着它不是未定义的,但它说“无法读取未定义”
【问题讨论】:
标签: javascript json angular typescript mean-stack