2017-09-05 3 views
0

双方向データバインディングが正しく機能しません。変数が角2を使用するように設定されていません

私は{user | json}を使用しますが、[(ngModel)] = "user.username"を使用するとエラーが表示されます。

インタフェースあなたは、非同期の方法でuserを設定している

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

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、これらは唯一の方法です。オプション1を使うことをお勧めします。 – Pengyy

関連する問題