![](/img/trans.png)
[英]TypeError: Cannot read property 'UserName' of undefined with Angular 2
[英]TypeError: Cannot read property 'username' of undefined Angular 2
我無法在angular 4應用程序的表單數據中獲取“用戶名”的值。 在html中,我有這行。
<section class="mdc-card__primary">
<div class="mdc-text-field">
<input type="text" id="username" class="mdc-text-field__input"
name="username" [(ngModel)]="loginValue.username" aria-controls="username-helptext">
<!-- <label for="username" class="mdc-text-field__label">Username</label> -->
<div class="mdc-text-field__bottom-line"></div>
</div>
<div class="mdc-text-field">
<input type="passsword" id="password" class="mdc-text-field__input"
name="password" [(ngModel)]="loginValue.password" aria-controls="password-helptext">
<!-- <label for="password" class="mdc-text-field__label">Password</label> -->
<div class="mdc-text-field__bottom-line"></div>
</div>
<div class="mdc-text-field">
<input type="hidden" id="ltype" class="mdc-text-field__input"
name="ltype" [(ngModel)]="loginValue.ltype" value="site">
<div class="mdc-text-field__bottom-line"></div>
</div>
</section>
在Logincomponents.ts中,我有這行
export class LoginComponent implements OnInit {
loginValue:any;
resnonseValue:any;
cookieValue:any;
errorMsg:any;
sessionValue = localStorage.getItem("userSession");
現在,在構建項目后出現以下錯誤。
main.bundle.js:1 ERROR TypeError: Cannot read property 'username' of undefined
因此,我的表單數據為空。
1)當我將其聲明為字符串時,它給我帶來了編譯時錯誤,即“用戶名”在字符串類型上不存在。 密碼和ltype相同。
2)我嘗試使用導出接口,但是它不起作用,存在相同的錯誤
3)我嘗試使用https://basarat.gitbooks.io/typescript/docs/types/index-signatures.html索引簽名
4)在開發模式下使用ng-serve不會出現錯誤或警告,但是在構建時,成功構建后將無法正常工作。
使用2種方式綁定之前,您需要初始化loginValue
:
loginValue = {
username : '',
password : '',
ltype : ''
}
或者您應該刪除2種方式的綁定並像
[ngModel]="loginValue?.username"
在組件中定義您的loginValue ,如下所示,這樣您就不會收到該錯誤:
loginValue:any = {};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.