I am working on an angular application. I have a method in which I am trying to assign values to the variables from the data received from API call. code
this.adminService.getConfigurations(input).subscribe(
data => {
this.data_Configuration = data[0];
this.data_Configuration_e = data[1]
this.data_Configuration.forEach(itm => {
itm.ApplicableDetails = []
this.data_Configuration_e
.filter(ent => ent.Id == itm.Id)
.forEach(e => {itm.ApplicableDetails.push(e)});
itm.ApplicableLevel.FirstFl = itm.ApplicableDetails.some(e => e.Nm == 'First') ? 'Y' : 'N'
itm.ApplicableLevel.SecondFl = itm.ApplicableDetails.some(e => e.Nm == 'Second') ? 'Y' : 'N'
});
My data_Configuration variable is defined from a interface
public data_Configuration : IConfiguraion[] = []
export interface IConfiguration {
Id: string;
Nm: string;
ApplicableLevel?: IApplicableLevels;
ApplicableDetails?: IDetails [];
}
export interface IApplicableLevels {
FirstFl?: string;
SecondFl?: string;
}
When I try to assign values to FirstFl using itm.ApplicableLevel.FirstFl = itm.ApplicableDetails.some(e => e.Nm == 'First') ? 'Y' : 'N' line I get an error cannot property FirstFl of undefined. How or where should I initialize the value of FirstFl to avoid this error?
FirstFlis undefined, it means thatitm.ApplicableLevelis undefined. You'll probably want to insertitm.ApplicableLevel = {};before assigning to it.IPrgmConfigurationbut the type definition isIConfiguraion. Which I assume is a typo while posting the question?{}is an object with named properties,[]is an array with index numbered elements.itm.ApplicableLevel=itm.ApplicableLevel || {} as IApplicableLevelsbefore assign FirstFl. When we use interface, some like {} as IConfiguration, the variable has all the properties of the interface but they areundefined