【问题标题】:Currently angular 5 is giving me different problems in firefox and chrome目前 angular 5 在 Firefox 和 chrome 中给我带来了不同的问题
【发布时间】: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...感谢您指出...

标签: angular angular5


【解决方案1】:

有两种方法可以解决这个问题:

您可以使用safe operator 解决此问题并删除2 way binding

<input type="text" name="UserName" #UserName ="ngModel" [ngModel]="user?.UserName">

组件端:

user : User = new User(); // this should initialise the user varible here

【讨论】:

  • @JohnStevenson ,你能接受答案吗?
【解决方案2】:

ERROR TypeError: "_co.user is undefined"

.ts 文件中声明的变量与.html file ngModel 中使用的变量不同时,通常会出现此错误

所以检查名称是否相同。

例如在.ts 文件中你声明了一个变量 user : any 如果您使用的是[(ngModel)] ="users.name",则在 .html 文件中 那么您将面临此错误。所以检查变量名:)

【讨论】:

    猜你喜欢
    • 2011-05-22
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多