如何订阅自定义模型 Angular 2?

How to subscribe on custom model 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}。但是当我改变模型时,什么都没有改变。

test 方法更改为:

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

将代码更改为

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

// Subscribe method

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

并添加

import "rxjs/add/observable/of";

编辑:这是一个笨蛋 https://plnkr.co/edit/KSOSvhe4C1uhTcLc7XML

可能您不需要订阅。您可以根据自己的目的使用 (ngModelChange)。更改模板输入:

<input [(ngModel)]="newEducationYearModel.name" 
       (ngModelChange)="modelChanged($event, newEducationYearModel)" 
       name="period" 
       type="text" 
       value=""/>

并向组件添加方法:

public modelChanged(year, newEducationYearModel) {
    console.log('year', year);
    console.log('newEducationYearModel', newEducationYearModel);
}

这里有一块木板https://plnkr.co/edit/HgzhovgFKczelCr3