简体   繁体   English

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

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

I'm practicing Angular-Forms using the template driven approach.我正在使用模板驱动的方法练习 Angular-Forms。 I'm aiming to build a UI to contain the result of my data like this:我的目标是构建一个 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>

So my data object in typescript will take these 3 props as strings I currently have this as the initializer: data: {email: string, sub: string, pass: string};所以我在 typescript 中的data object 将把这 3 个道具作为字符串,我目前有这个作为初始化器: data: {email: string, sub: string, pass: string};

And in the constructor I have:在构造函数中我有:

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

And on form submit I have:在提交表单时,我有:

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

On reload I'm getting: ERROR TypeError: Cannot set property 'email' of undefined重新加载时我得到: ERROR TypeError: Cannot set property 'email' of undefined

I'm 99% sure it's because of the way I'm declaring this object.我 99% 确定这是因为我声明这个 object 的方式。 But it seems like I declare it -> give types to it's properties -> give default values in the constructor.但似乎我声明了它->为其属性提供类型->在构造函数中提供默认值。 But in the constructor this.data is undefined.但是在构造函数中 this.data 是未定义的。

What's the typescript way of doing this? typescript 这样做的方法是什么?

Data is not defined so you can not append properties to the undefined object.数据未定义,因此您不能将 append 属性赋予未定义的 object。 Please try this in your constructor:请在您的构造函数中尝试此操作:

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

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

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