我有以下接口可用作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 { .....
它通过条件,表示它不是未定义的,但是它说“无法读取未定义的”
最佳答案
过滤方法找不到匹配项。因此,可观察到的结果是undefined
。
getBySector(sector): Observable<IIndustrySectors| undefined> {
return this.getMainIndustrySectors().pipe(
map((products: IIndustrySectors[]) => products.find(p => p.IndustrySector === sector)));
// ^^^ matches none
}