我創建了一個WorkingData
對象,我使用該對象在組件之間傳遞某些數據。該對象的一個成員是today
這是包含當前日期的Date
對象。我想在setInterval
功能來更新這個每一秒,但workingData
對象在這一點給我的控制檯錯誤是不確定的:Service的數據無法訪問Angular2的OnInit
Cannot set property 'today' of undefined
app.component.ts
import { Component, OnInit, AfterContentChecked } from '@angular/core';
import { WorkingData } from './services/working-data/working-data';
import { WorkingDataService } from './services/working-data/working-data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [ WorkingDataService ]
})
export class AppComponent implements OnInit, AfterContentChecked {
workingData: WorkingData;
constructor(public _workingDataService: WorkingDataService) { }
getWorkingData() {
this._workingDataService.getWorkingData().then(workingData => this.workingData = workingData);
}
ngOnInit() {
this.getWorkingData();
console.log('OnInit()');
console.log(this.workingData); // doesn't work
// setInterval(this.updateTime(), 1000); // doesn't work
}
ngAfterContentChecked() {
console.log('AfterContentChecked()');
console.log(this.workingData); // doesn't work the first call but does after it is called again at some later point
// setInterval(this.updateTime(), 1000); // doesn't work
}
updateTime() {
this.workingData.today = new Date();
}
}
工作數據。 service.ts
import {Injectable} from '@angular/core';
import {WorkingData} from './working-data';
import {WORKINGDATA} from './mock-working-data';
@Injectable()
export class WorkingDataService {
getWorkingData(): Promise<WorkingData> {
return Promise.resolve(WORKINGDATA);
}
}
我相信的服務是有效的,因爲它使用workingData
對象和生成視圖s後續AfterContentChecked
LifeCycle,但我似乎無法使用對象OnInit
。我懷疑我沒有正確使用LifeCycle鉤子,但我不明白如何正確實施它。 我該如何立即開始setInterval
?
爲什麼不在回調中設置'today'(並啓動更新間隔)?當您確實可以訪問'this.workingD ata'? – jonrsharpe
'this._workingDataService.getWorkingData()'是異步的。你不能同時在'ngOnInit'中得到它的結果。你不應該。 *在setInterval函數*中每秒更新一次,可觀察是比承諾更好的選擇。 – estus
請記住,您可以從一個時間間隔創建一個Observable並訂閱它。 'Observable.interval(1000)' – nicowernli