繁体   English   中英

初始化一个空的 typescript object,但定义它的属性

[英]Initialize an empty typescript object, but define it's properties

我正在使用模板驱动的方法练习 Angular-Forms。 我的目标是构建一个 UI 来包含我的数据结果,如下所示:

            <hr>
            <div class="well well-lg">
              <p>Email Address: <span class="bg-info">{{data.email}}</span></p>
              <p>Subscription Type: <span class="bg-info">{{data.sub}}</span></p>
              <p>Password: <span class="bg-info">{{data.pass}}</span></p>
            </div>

所以我在 typescript 中的data object 将把这 3 个道具作为字符串,我目前有这个作为初始化器: data: {email: string, sub: string, pass: string};

在构造函数中我有:

this.data.email = '';
this.data.sub = '';
this.data.pass = '';

在提交表单时,我有:

if(this.myForm.valid){
      this.data.email = this.myForm.value.email;
      this.data.sub = this.myForm.value.subscription;
      this.data.pass = this.myForm.value.password;
      this.myForm.reset();
    }

重新加载时我得到: ERROR TypeError: Cannot set property 'email' of undefined

我 99% 确定这是因为我声明这个 object 的方式。 但似乎我声明了它->为其属性提供类型->在构造函数中提供默认值。 但是在构造函数中 this.data 是未定义的。

typescript 这样做的方法是什么?

数据未定义,因此您不能将 append 属性赋予未定义的 object。 请在您的构造函数中尝试此操作:

this.data = {
    email: '',
    sub: '',
    pass: '',
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM