【问题标题】:Undefined validation does not work-angular 11未定义的验证不起作用-角度 11
【发布时间】:2021-06-15 08:33:28
【问题描述】:

我有一个组件,我订阅了一个 Customer 对象,这个客户有一个电话是字符串,但它可以是未定义的,因为在数据库中是空的,所以后端不会发送它。这就是为什么我需要在打印 html 中的数据之前进行验证。我尝试为什么简单的 if(this.customer.movi​​lPhone) 但我收到一条错误消息:无法读取未定义的属性“movilPhone”。然后我尝试了 if (this.customer.movi​​lPhone !== 'undefined') 但我也遇到了同样的错误。我使用的第一个选项应该可以工作,为什么没有?在此先感谢:)

我的代码是这个:

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();
   }
}

【问题讨论】:

    标签: angular typescript validation undefined-reference angular11


    【解决方案1】:

    问题:

    this.customer.movilPhone 抛出错误,因为 this.customer 没有赋值。预计是nullundefined


    解决方案:

    你需要确保this.customer被赋值然后只能访问this.customer.movilPhone.你可以通过Typescript Optional Chaining来实现。

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

    【讨论】:

    • 感谢您的解释和解决方案。它现在可以工作了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多