gpt4 book ai didi

javascript - 错误类型错误 : Cannot read property X of undefined

转载 作者:行者123 更新时间:2023-12-01 01:49:34 26 4
gpt4 key购买 nike

我有以下接口(interface)用作 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: Cannot read property 'dataSubjectCategories' of undefined "

不过它会打印值。

这是为什么呢?

要做的是,根据该部门,我获取与其相关的其他数据“响应”,并填充绑定(bind)到下拉列表的字符串类型数组。它工作正常,但下图显示了选择子扇区后会发生什么:enter image description here

请帮助我,我是新手,我对此感到非常厌倦:((谢谢。

编辑:当我说

 if (response == undefined) {
throw new Error("sector not found");
}
else { .....

它通过了条件,这意味着它不是未定义的,但它说“无法读取未定义”

最佳答案

过滤方法未找到匹配项。所以可观察的结果是未定义

getBySector(sector): Observable<IIndustrySectors|  undefined> {
return this.getMainIndustrySectors().pipe(
map((products: IIndustrySectors[]) => products.find(p => p.IndustrySector === sector)));
// ^^^ matches none
}

关于javascript - 错误类型错误 : Cannot read property X of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51656492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com