我有以下自定义模型:
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:无法读取属性&#39;订阅&#39;未定义的
我做错了什么?
模板是:
{{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 :(得分: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";
答案 1 :(得分:1)
将test
方法更改为:
public test(): Observable<CreateEducationYear> {
return Observable.of(this.newEducationYearModel);
}
答案 2 :(得分: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);
}