2017-08-17 18 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

+0

我做了修改,但仍然可以看到在控制檯 – user3573738

+0

沒有你現在應該有一個空的對象。您可以通過添加改變你的構造:'this.newEducationYearModel.year = 2000;' – avilao

+0

我從模板修改該對象並查看模板的變化:{{newEducationYearModel}},但不是在Observel – user3573738

1

變化test方法是這樣的:

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

我已經更改改爲觀看這個對象,變化,但仍看不到任何控制檯 – user3573738