Utilizing a workingData
service that stores crucial data across my application, it provides an observable to the Mock workingData
object.
@Injectable()
export class WorkingDataService {
getWorkingData(): Observable<WorkingData> {
return Observable.of(WORKINGDATA);
}
getSelectedDate(): Observable<Date> {
return Observable.of(WORKINGDATA.selectedDate);
}
}
Within the workingData
object, there exists a date field known as selectedDate
.
export const WORKINGDATA: WorkingData = {
today: new Date(),
selectedDate: new Date('11-15-2016'),
targetDate: new Date(),
data: []
};
This specific value can be modified by interacting with the "previous month" or "next month" buttons: https://i.sstatic.net/DyCtZ.png
By doing so, the following function (or its counterpart incrementDate()
) within the cal-nav
component is triggered:
decrementDate(): void {
let newDate = new Date(this.workingData.selectedDate.getDate());
newDate.setMonth(newDate.getMonth() - 1);
this.workingData.monthPrior = newDate;
}
The observable automatically updates the display in all components where the workingDate
service is injected. However, I now aim to activate a function within the month
component (which is a sibling of the cal-nav
component) every time the workingData.selectedDate
changes, regardless of the originating component. How can I accomplish this?
UPDATE: It is now necessary to explicitly subscribe to the selectedDate
property.
ngOnInit(): void {
this.getWorkingData();
this.getSelectedDate(); // Just added
}
getSelectedDate(): void{
this._workingDataService.getSelectedDate().subscribe(selectedDate => {this.myFunc();});
}
myFunc(){
console.log('working');
}
While this successfully invokes myFunc()
during initialization, it fails to do so when the value is updated.