【问题标题】:variable not set to using angular 2变量未设置为使用角度 2
【发布时间】:2017-09-05 01:59:34
【问题描述】:

双向数据绑定无法正常工作。

我可以使用 {user | 恢复数据吗? json},但使用 [(ngModel)] = "user.username" 时会显示错误。

界面

export interface UserModel {

        username?: any;
        email?: any;
        first_name: any;
        last_name: any;
        profile: ProfileModel;

}

interface ProfileModel {

        nome_empresa: any;
        cnpj: any;
}

组件

import { Component, OnInit } from '@angular/core';
import { PerfilService } from './perfil.service';
import { UserModel } from './user.model';

@Component({
  selector: 'mw-perfil',
  templateUrl: './perfil.component.html'
})
export class PerfilComponent implements OnInit {


  user: UserModel = new UserModel();

  constructor(private perfil: PerfilService) { }

  ngOnInit() {
    this.perfil.get().subscribe((perfil) => {
      this.user = perfil;

    })

  }

}

模板

<input id="username" class="form-control" data-error="Usuário inválido" placeholder="" required="required" type="text" name="username" [(ngModel)]="user.username">

PerfilComponent.html:31 错误类型错误:无法读取属性 未定义的“用户名” 在 Object.View_PerfilComponent_0._co [作为 updateDirectives] (PerfilComponent.html:31) 在 Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13058) 在 checkAndUpdateView (core.es5.js:12238) 在 callViewAction (core.es5.js:12603) 在 execComponentViewsAction (core.es5.js:12535) 在 checkAndUpdateView (core.es5.js:12244) 在 callViewAction (core.es5.js:12603) 在 execEmbeddedViewsAction (core.es5.js:12561) 在 checkAndUpdateView (core.es5.js:12239) 在 callViewAction (core.es5.js:12603)

【问题讨论】:

    标签: angular


    【解决方案1】:

    您正在通过异步方式设置user。即使您在ngOnInit 调用异步调用,数据也不会准备好。

    由于您在ngModel 使用user.username,因此此处不能使用safe navigator operator。所以唯一的解决方案是先初始化user,下面的方法可以解决问题:

      // option1
      user: UserModel = new UserModel();
    
      // option2
      constructor(private perfil: PerfilService) { 
        this.user = new UserModel();
      }
    
      // option3
      ngOnInit() {
        this.user = new UserModel();
        this.perfil.get().subscribe((perfil) => {
          this.user = perfil;
    
        })
      }
    

    【讨论】:

    • 非常感谢。这是将银行数据加载到表单中的最佳方式还是有更好的方式?
    • perfil.component.ts (11,25): 'UserModel' 仅指一种类型,但在这里用作值。
    • @user2716095 AFAIK,这些是唯一的方法。我建议您使用 option1。
    • 没有用。 perfil.component.ts (11,25): 'UserModel' 仅指一种类型,但在这里用作值。
    • @user2716095 您可以发布您现在所做的更改吗?看看github.com/Microsoft/TypeScript/issues/11807
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    相关资源
    最近更新 更多