【发布时间】:2019-10-31 23:41:54
【问题描述】:
几天以来我一直在尝试解决,但仍然遇到错误。将 angular cli、nodejs 更新到最新版本,但仍然出现以下错误。我再次对 Firefox 和 chrome 中不同的错误感到困惑。请帮助我,我刚刚开始学习我的工作。我仍然很困惑我的代码是否有错误,或者浏览器是否像我一样感到困惑。
在 Chrome 中
'ERROR TypeError: Cannot read property 'UserName' of undefined
在火狐中
TypeError: _co.user is undefined
代码 sn-ps
<input type="text" name="UserName" #UserName ="ngModel" [(ngModel)]="user.UserName">
sign-up-components.ts
import { Component, OnInit } from '@angular/core';
import { User } from '../shared/user.model';
import { NgForm } from '@angular/forms';
import { UserService } from '../shared/user.service';
@Component({
selector: 'app-sign-up',
templateUrl: './sign-up.component.html',
styleUrls: ['./sign-up.component.css']
})
export class SignUpComponent implements OnInit {
user : User;
constructor( private userService : UserService) { }
ngOnInit() {
}
OnSubmit(form : NgForm){
this.userService.addUser(form.value).subscribe((data : any)=> {
if(data.Succeeded ==true){
console.log("transferred successfull");
}
});
}
}
user.model
export class User {
UserName: string;
Password: string;
Email: string;
FirstName: string;
LastName: string;
}
如果有人经历过这个,请告诉我解决方案。 因为我已经开始了 angular 我猜我已经更新了两次 cli。一开始没有这样的错误。但自从我更新了错误来了。
【问题讨论】:
-
您实际上从未设置过
user,因此它将是未定义的。您需要将其设置在某处或相应地对待 undefined/null。 -
是的,你是对的,Alex...感谢您指出...