2017-09-05 32 views
0

雙向數據綁定無法正常工作。變量未設置爲使用角度2

我可以使用{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: Cannot read property 'username' of undefined at Object.View_PerfilComponent_0._co [as updateDirectives] (PerfilComponent.html:31) at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13058) at checkAndUpdateView (core.es5.js:12238) at callViewAction (core.es5.js:12603) at execComponentViewsAction (core.es5.js:12535) at checkAndUpdateView (core.es5.js:12244) at callViewAction (core.es5.js:12603) at execEmbeddedViewsAction (core.es5.js:12561) at checkAndUpdateView (core.es5.js:12239) at callViewAction (core.es5.js:12603)

回答

0

您是通過異步方式設置user。即使您在ngOnInit處調用異步調用,數據也不會準備就緒。

由於您使用user.usernamengModel,因此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; 

    }) 
    } 
+0

太謝謝你了。這是將銀行數據加載到表單還是更好的方法? –

+0

perfil.component.ts(11,25):'UserModel'僅指一個類型,但在這裏被用作一個值。 –

+0

@ user2716095 AFAIK,這是唯一的方法。我建議你使用option1。 – Pengyy