【问题标题】:Angular - Property 'email' does not exist on type '{}' with AoT compilationAngular - 使用 AoT 编译的类型“{}”上不存在属性“电子邮件”
【发布时间】:2017-10-12 18:13:36
【问题描述】:

我在 ng:...template.html 中遇到错误 ERROR: Property 'email' does not exist on type '{}' whencompile using Angular Cli > ng build --prod --aot

表单模板:

        <form (ngSubmit)="login()" #loginForm="ngForm">

            <input [(ngModel)]="user.email" id="email"
                   type="email" class="validate" name="email" required>
            <label for="email">Email</label>

            ...

        </form>

登录组件:

export class LoginComponent {

    public user = {};
    public errorMsg = '';
    email: any;
    password: any;

constructor(
...
) {

在表单组件中添加类型 email:string 或 email:any 并不能解决问题。它似乎指的是工厂 Angular 组件 {}。我怎样才能绕过这个错误?

【问题讨论】:

  • 你的组件的代码在哪里?你读过代码吗?您正在使用的email 字段位于组件的user 字段上。不在组件上。
  • 值在哪里以及如何分配给user
  • 我想这应该对用户有所帮助:any = {}

标签: angular


【解决方案1】:

您还可以分配对象类型。

public user = <{email: string}>{};

【讨论】:

    【解决方案2】:

    您的问题来自用户实例化。

    以下实例化应该可以工作:

    public user = {'email': ''}
    

    但密码可能会发生类似的错误(取决于您在模板中的使用方式)。

    在这种情况下,实例化应该是:

    public user = {'email': '',
                   'password': ''
                  }
    

    更好的方法是创建一个用户类。 user.ts 应该如下所示:

    export class User {
    
        constructor(public email?: string,
                    public password?: string) { }
    
    }
    

    然后像这样在你的 LoginComponent 中实例化用户:

    public user: User = new User();
    

    【讨论】:

      【解决方案3】:
      public user = {};
      

      此用户对象没有任何名为 email 的属性。改成

      public user = { email: '' }; 
      

      例如。

      【讨论】:

      • 完美。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 2020-07-05
      • 2019-01-30
      • 2018-09-11
      • 1970-01-01
      相关资源
      最近更新 更多