I use a workingData service that holds data that permeates my application. It returns 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);
}
}
One property on the workingData object is a date field called selectedDate.
export const WORKINGDATA: WorkingData = {
today: new Date(),
selectedDate: new Date('11-15-2016'),
targetDate: new Date(),
data: []
};
This value can be updated by clicking the "previous month" or "next month" buttons:

This triggers the following function (or it's incrementDate() counterpart) in the cal-nav component:
decrementDate(): void {
let newDate = new Date(this.workingData.selectedDate.getDate());
newDate.setMonth(newDate.getMonth() - 1);
this.workingData.monthPrior = newDate;
}
The observable updates the view in all comopnents in which the workingDate service is injected, but I now need to trigger a funtion in the month component (which is a sibling of the cal-nav component). How trigger a function in the month componenet each time workingData.selectedDate is updated, even if it is updated from a different component?
UPDATE: I now subscribe to the selectedDate property seperately.
ngOnInit(): void {
this.getWorkingData();
this.getSelectedDate(); // Just added
}
getSelectedDate(): void{
this._workingDataService.getSelectedDate().subscribe(selectedDate => {this.myFunc();});
}
myFunc(){
console.log('working');
}
This fires myFunc() oninit but not when the the value updates.
You can just subscribe to your Observable in your code
this.myObservable.subscribe( data => {
myFunction();
});
If that does not fulfil your needs then you have to provide more code or some sequence of what you exactly need
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With