chink
chink

Reputation: 1653

How to initialize variable to avoid 'cannot read property <variable> undefined'?

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?

Upvotes: 0

Views: 125

Answers (1)

Barremian
Barremian

Reputation: 31125

Most probably it's a TS Lint error because the itm.ApplicableLevel isn't initialized yet. You could instead try to initialize the ApplicableLevel property with both it's sub-properties FirstFl and SecondFl as an object instead.

Also you could skip an additional level of iterations of the data_Configuration_e array by replacing the unnecessary filter with an if in the forEach loop.

Try the following

this.data_Configuration.forEach(itm => {
  itm.ApplicableDetails = [];
  
  this.data_Configuration_e.forEach(e => {
    if (ent.Id == itm.Id) {
      itm.ApplicableDetails.push(e);
    }
  });

  itm.ApplicableLevel = <IApplicableLevels>{
    FirstFl: (itm.ApplicableDetails.some(e => e.Nm == 'First')) ? 'Y' : 'N',
    SecondFl: (itm.ApplicableDetails.some(e => e.Nm == 'Second')) ? 'Y' : 'N'
  };
});

Upvotes: 1

Related Questions