2017-08-17 12 views
0

カスタムモデルAngular 2を購読するには?私は、次のカスタムモデルを持っている

export class CreateEducationYear { 

    public year: number; 
    public name: string; 

} 

は、私はこのようなコンポーネントでこれを使用します。

public newEducationYearModel: Observable<CreateEducationYear>; 
constructor() { 
    this.newEducationYearModel = new Observable<CreateEducationYear>(); 
} 

// Subscribe method 

public test(): Observable<CreateEducationYear> { 
    return this.newEducationYearModel; 
} 

// Listening 

ngOnInit() { 
    this.test().subscribe(data => { 
     console.log(data); 
    }); 
    } 

私はエラーを取得する:

TypeError: Cannot read property 'subscribe' of undefined

は私が間違って何をしますか?

テンプレートは次のとおりです。

{{newEducationYearModel | json }} 
<div class="filter-search-item-sub col-md-3"> 
    <label>Название периода</label> 
    <input [(ngModel)]="newEducationYearModel.name" name="period" type="text" value=""/> 
</div> 

最初の打ち上げ後、私は、コンソールでCreateEducationYear {year: 2000}を参照してください。しかし、さらに私がモデルを変えても、何も変わりません。以下のように見えるように

+0

あなたはカスタムオブジェクトを使用して結果をモックしようとしていますか? – Arun

+0

あなたは何をしようとしていますか?観察可能な()を返しますか? –

+0

テンプレートで変更されたときにこのオブジェクトの変更を確認しようとしました – user3573738

答えて

2

public newEducationYearModel: CreateEducationYear; 
constructor() { 
    this.newEducationYearModel = new CreateEducationYear(); 
} 

// Subscribe method 

public test(): Observable<CreateEducationYear> { 
    return Observable.of(this.newEducationYearModel); 
} 

にコードを変更し、

import "rxjs/add/observable/of"; 

編集を追加

:ここplunker https://plnkr.co/edit/KSOSvhe4C1uhTcLc7XML

があります210
+0

変更を加えましたが、コンソールには何も表示されません – user3573738

+0

今は空のオブジェクトが必要です。 'this.newEducationYearModel.year = 2000;' – avilao

+0

このオブジェクトをテンプレートから変更して、テンプレートの変更を見てみましょう:{{newEducationYearModel}}、Observeではなく – user3573738

1

変更test方法:

public test(): Observable<CreateEducationYear> { 
    return Observable.of(this.newEducationYearModel); 
} 
+0

変更を加えましたがコンソールに何も表示されません – user3573738

関連する問題