In my code, I have a custom WorkingData
object that is responsible for passing specific data between components. One of the properties in this object is today
, which holds the current date as a Date
object. My goal is to continuously update this property every second using a setInterval
function. However, I'm encountering an issue where the workingData
object is undefined at this point, resulting in the following console error:
Cannot set property 'today' of undefined
This problem occurs in the app.component.ts
file:
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();
}
}
The service file working-data.service.ts
looks like this:
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);
}
}
While the service seems to be functioning correctly when generating the view and logging data in the AfterContentChecked
lifecycle hook, I'm unable to access the workingData
object in the OnInit
lifecycle hook. It appears that there might be an issue with how I'm utilizing the lifecycle hooks. How can I address this problem and initiate the setInterval
immediately?