Search code examples
angulartypescriptvalidationundefined-referenceangular11

Undefined validation does not work-angular 11


I have a component where I subscribe to get an Customer object, this customer has a telephone that is string but It can comes undefined, because in the database is empty so the backend does not send it. That is why I need to make a validation before I print the data in the html. I try why the simple if(this.customer.movilPhone) but I got a error message: Cannot read property 'movilPhone' of undefined. Then I tried with if (this.customer.movilPhone !== 'undefined') but also I got the same error. The first option I used should work, why it did not? Thanks in advance :)

My code is this one:

export interface CustomerModel {
   dateOfBirth?: string;
   country?: string;
   firstName?: string;
   lastName?: string;
   city?: string;
   movilPhone?: string;
   email?: string;
}

export class AppointmentComponent implements OnInit, OnDestroy {
   public destroyed = new Subject<any>();
   customer: CustomerModel;
   constructor(private readonly translate: TranslateService,
         private readonly sharingDataService: SharingDataService,
         private readonly router: Router,
         private readonly activatedRoute: ActivatedRoute,
         private readonly breakpointObserver: BreakpointObserver,
         private readonly  customerService: CustomerService) {
   }

   getCustomerData(): void{
       this.customerService.getCustomer().subscribe(data => this.customer = data);
       this.createArrayOfPhones();
   }

   isValid(telephone: string): boolean {
       return typeof telephone !== 'undefined';
   }

   createArrayOfPhones(): void {
       const telephones = {} as Array<string>;
       this.customer.mobilePhone;
       if (this.customer.movilPhone) { // Not Works
           telephones.push(this.customer.movilPhone);
       }
       console.log('Before');
       if (telephones) { // Works
           for (let i = 0; i < telephones.length; i++){
               console.log('Telephones ' + telephones[i]);
           }
       }
    }

   ngOnDestroy(): void {
       this.destroyed.next();
       this.destroyed.complete();
       this.destroyed.unsubscribe();
   }
}

Solution

  • ISSUE:

    this.customer.movilPhone throws error because this.customer is not assigned with value. Expected it is null or undefined.


    SOLUTION:

    You need to ensure that this.customer is assigned with value then only access this.customer.movilPhone. You can achieve it with Typescript Optional Chaining.

    if (this.customer?.movilPhone) {
        telephones.push(this.customer.movilPhone);
    }