Nat*_*May 3 javascript observable typescript angular2-changedetection angular
我使用的workingData服务包含渗透到我的应用程序的数据.它向Mock workingData对象返回一个observable .
@Injectable()
export class WorkingDataService {
getWorkingData(): Observable<WorkingData> {
return Observable.of(WORKINGDATA);
}
getSelectedDate(): Observable<Date> {
return Observable.of(WORKINGDATA.selectedDate);
}
}
Run Code Online (Sandbox Code Playgroud)
workingData对象上的一个属性是名为的日期字段selectedDate.
export const WORKINGDATA: WorkingData = {
today: new Date(),
selectedDate: new Date('11-15-2016'),
targetDate: new Date(),
data: []
};
Run Code Online (Sandbox Code Playgroud)
这会incrementDate()在cal-nav组件中触发以下函数(或它的对应函数):
decrementDate(): void {
let newDate = new Date(this.workingData.selectedDate.getDate());
newDate.setMonth(newDate.getMonth() - 1);
this.workingData.monthPrior = newDate;
}
Run Code Online (Sandbox Code Playgroud)
observable更新了workingDate注入服务的所有comopnents中的视图,但我现在需要在month组件中触发一个funtion (这是组件的兄弟cal-nav).每次更新组件中的某个功能是如何更新的,即使它是从另一个组件更新的?monthworkingData.selectedDate
更新:我现在selectedDate单独订阅该物业.
ngOnInit(): void {
this.getWorkingData();
this.getSelectedDate(); // Just added
}
getSelectedDate(): void{
this._workingDataService.getSelectedDate().subscribe(selectedDate => {this.myFunc();});
}
myFunc(){
console.log('working');
}
Run Code Online (Sandbox Code Playgroud)
这会触发myFunc()oninit但不会在值更新时触发.
小智 5
您可以在代码中订阅Observable
this.myObservable.subscribe( data => {
myFunction();
});
Run Code Online (Sandbox Code Playgroud)
如果这不能满足您的需求,那么您必须提供更多代码或一些您确切需要的序列
| 归档时间: |
|
| 查看次数: |
3944 次 |
| 最近记录: |