微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

未定义的验证不起作用-angular 11

如何解决未定义的验证不起作用-angular 11

我有一个组件,我在其中订阅一个 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();
   }
}

解决方法

问题:

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


解决方案:

您需要确保为 this.customer 分配了值,然后只能访问 this.customer.movilPhone. 您可以使用 Typescript Optional Chaining 来实现。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?