当可观察属性更改时,Angular2触发器函数

时间:2016-12-07 20:33:14

标签: javascript angular typescript observable angular2-changedetection

我使用workingData服务来保存遍及我的应用程序的数据。它将一个observable返回给Mock workingData对象。

@Injectable()
export class WorkingDataService {
  getWorkingData(): Observable<WorkingData> {
    return Observable.of(WORKINGDATA);
  }
  getSelectedDate(): Observable<Date> {
    return Observable.of(WORKINGDATA.selectedDate);
  }
}

workingData对象上的一个属性是名为selectedDate的日期字段。

export const WORKINGDATA: WorkingData = {
  today: new Date(),
  selectedDate: new Date('11-15-2016'),
  targetDate: new Date(),
  data: []
};

点击“上个月”或“下个月”按钮可以更新此值: enter image description here

这会触发incrementDate()组件中的以下函数(或cal-nav对应函数):

decrementDate(): void {
  let newDate = new Date(this.workingData.selectedDate.getDate());
  newDate.setMonth(newDate.getMonth() - 1);
  this.workingData.monthPrior = newDate;
}

observable更新注入了workingDate服务的所有comopnents中的视图,但我现在需要在month组件(cal-nav的兄弟中触发一个函数} 零件)。 每次更新month组件时workingData.selectedDate组件中的功能是如何更新的,即使它是从其他组件更新的?

更新:我现在单独订阅selectedDate属性。

ngOnInit(): void {
  this.getWorkingData();
  this.getSelectedDate(); // Just added
}

getSelectedDate(): void{
  this._workingDataService.getSelectedDate().subscribe(selectedDate => {this.myFunc();});
}
myFunc(){
  console.log('working');
}

这会触发myFunc() oninit,但不会在值更新时触发。

1 个答案:

答案 0 :(得分:5)

您可以在代码中订阅您的Observable

this.myObservable.subscribe( data => {
  myFunction();
 });

如果这不能满足您的需求,那么您必须提供更多代码或一些您确切需要的序列

相关问题