[英]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.