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

问题描述 投票:-1回答:3

我有以下自定义模型:

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:无法读取undefined的属性'subscribe'

我做错了什么?

模板是:

{{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}。但是当我改变模型时,没有任何改变。

angular angular2-observables
3个回答
1
投票

可能你不需要订阅。您可以将(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


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


1
投票

test方法更改为:

public test(): Observable<CreateEducationYear> {
    return Observable.of(this.newEducationYearModel);
}
© www.soinside.com 2019 - 2024. All rights reserved.