33
訪問輸入我有一個簡單的角度2組件與@Input
,我綁定到模板。模板顯示輸入的數據,但我不能從構造訪問:無法從我的控制器/構造
import {Component, View, bootstrap, Input} from 'angular2/angular2';
import DataService from './data-service';
@Component({
selector: 'app-cmp'
})
@View({
template: `{{data.firstName}} {{data.lastName}}` //-> shows the correct 'data'
})
export default class NamesComponent {
@Input() data: any;
constructor(dataService: DataService) {
console.log(this.data);//undefined
}
}
這裏是一個plunker用一個例子(見「的名字 - component.ts」)。
我在做什麼錯?
根據較新的API,你實際上需要從「angular2/angular2」導入的OnInit,然後改變你的類來實現的OnInit所以它應該是這樣的: 出口默認類NamesComponent實現的OnInit { 。 .. } – jgo
這個答案仍然適用於2.0.0-beta.8。因此服務可以在構造函數中初始化(構造函數(dataService:DataService){this.dataService = dataservice})。但是,使用輸入作爲參數的實際提取服務需要在ngOnInit()函數內發生(使用類似ngOnInit()的函數){var data = this.dataService; this.dataService.getData(data).subscribe .. 。 –