I have this Interface that serves as a type for a JSON file:
export interface IIndustrySectors {
IndustrySector: string;
isSelected: string;
dataSubjectCategories:string[];
dataTypeCategories:string[];
SubIndustries:[{
IndustrySector: string;
isSelected: string;
dataSubjectCategories:string[];
dataTypeCategories:string[];
SubIndustries:[{}]
}]
}
Additionally, there are two services:
// Retrieve all 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)));
}
Highlighted below is a snippet from the JSON file:
[
{
"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":[]
}
]
}
]
The issue arises when calling the service "getBySector" using the code below:
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])
}
}
})
An error is thrown:
TypeError: Cannot read property 'dataSubjectCategories' of undefined "
However, the values are still printed out.
What could be causing this?
My goal is to retrieve additional data related to the selected sector in the "response" and populate an array of type string to bind to a dropdown list. While it seems to work fine initially, this image illustrates what happens after selecting the sub-sector:https://i.sstatic.net/wEtlQ.png
Please assist me with this, as I am new to this and getting quite frustrated :(( Thank you.
EDIT: When doing the following check:
if (response == undefined) {
throw new Error("sector not found");
}
else { .....
The condition passes despite claiming "cannot read undefined".