变量未设置为使用角度2

时间:2017-09-05 01:59:35

标签: angular

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

我可以使用{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;
}

componente

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 ERROR TypeError:无法读取属性   “用户名”未定义       at Object.View_PerfilComponent_0._co [as updateDirectives](PerfilComponent.html:31)       at 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)       at execEmbeddedViewsAction(core.es5.js:12561)       在checkAndUpdateView(core.es5.js:12239)       在callViewAction(core.es5.js:12603)

1 个答案:

答案 0 :(得分:0)

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

由于您在user.username使用ngModel,因此此处无法使用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;

    })
  }