2

我使用一個workingData服務來保存滲入我的應用程序的數據。它將可觀測值返回給Mock workingData對象。在workingData對象當可觀察到的屬性發生變化時,Angular2觸發函數

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

一個屬性是叫selectedDate日期字段。在cal-nav組件 enter image description here

這會觸發下面的函數(或它的incrementDate()對應):

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

這個值可以通過點擊「上月」或「下月」按鈕更新

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

可觀察的更新所有在其中workingDate服務注入的comopnents視圖,但我現在需要在觸發一個功能組件(它是cal-nav組件的同級)。 每次更新workingData.selectedDate時,如何在month組件網絡中觸發功能,即使它是從其他組件更新的?

更新:我現在單獨訂閱selectedDate屬性。

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

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

這會觸發myFunc() oninit,但值不會更新。

回答

4

您可以直接訂閱您可觀察到在你的代碼

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

如果不能滿足您的需要,那麼你必須提供更多的代碼或什麼你到底需要

+0

我不知道一些序列想要觸發該功能,除非該特定屬性發生變化,而不是整個對象。有沒有辦法實現這一點? –

+0

是單獨觀察該屬性。 – lastWhisper

+0

只是告訴我們一個例子 – lastWhisper

相關問題