TypeScript无法读取未定义的属性-Angular 7



我有这个电子邮件模型:

export class Email{
to: Array<
{
email: string
name: string
}
>
from: {
email: string
name: string
}
cc: Array<
{
email: string
name: string
}
>
bcc: Array<
{
email: string
name: string
}
>
subject: string
body: string
type: string
}

然后我导入电子邮件模型,并在类中声明如下:

import { Email } from '@/models/email';
export class BuilderJobComponent implements OnInit {
emailJobData: Email

稍后,在类方法中,我尝试设置一个值,但未定义。我有什么不明白的?

无法读取未定义的属性"from">

this.emailJobData.from.email = email
this.emailJobData.from.name  = name
// set the To address
if( Recipient ){
this.emailJobData.to.push({ email: Recipient, name: '' })
}

您声明了变量emailJobData,但没有为其赋值。因此,它的值为undefined。undefined没有任何属性。

冒号后的类型只定义可以分配给变量的类型,但不分配任何值。

在您的代码中,替换

emailJobData: Email;

带有

emailJobData: Email = new Email();

你应该表现得很好。

编辑:为了进一步解决这个问题,最好在类中设置一个构造函数,将类中的值/对象初始化为预期值。当然,这取决于业务逻辑——有时你会期望未定义的值,而不是空数组/空对象等,所以相应地更新——下面只是一个例子。

export class AddressWithDisplayValue {
email: string;
name: string;
}
export class Email{
from: AddressWithDisplayValue;
to: AddressWithDisplayValue[];
cc: AddressWithDisplayValue[];
bcc: AddressWithDisplayValue[];
subject: string;
body: string;
type: string;

constructor() {
this.from = new AddressWithDisplayValue();
this.to = [];
this.cc = [];
this.bcc = [];
}
}

然后,在用emailJobData = new Email()初始化后,您将能够设置这些属性,例如

this.emailJobData.from.email = email;

最新更新