最好的方法是使用 Events:
在您的根页面中,订阅自定义事件,以在每次发布该事件时执行一些代码:
import { Events } from 'ionic-angular';
constructor(public events: Events) {
events.subscribe('status:updated', (updatedData) => {
// You can use the updatedData to update the view
// ...
});
}
// Clean up the subscription when the page is about to be destroyed
ionViewWillUnload() {
this.events.unsubscribe('status:updated');
}
当用户更改该数据时,将该事件发布到任何其他页面:
import { Events } from 'ionic-angular';
constructor(public events: Events) {}
yourMethod(): void {
// Your custom logic...
// ...
// Now you can publish the event to update the root page (and any other page subscribed to this event)
this.events.publish('status:updated', updatedData);
}
编辑
另一种方法是使用共享服务,并使用Subject 发布/订阅更改。结果与 Ionic Event 的 非常相似,但在这种情况下,您需要添加一个共享服务,然后在数据更新时使用它。我更喜欢离子事件,但以防万一,你可以这样做:
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MySharedService {
public onDataChange: Subject<any>;
constructor() {
this.onDataChange = new Subject<any>();
}
public publishUpdate(newData): void {
// Send the data to all the subscribers
this.onDataChange.next(newData);
}
}
现在在您的根页面中,使用共享服务订阅更改
import { Subscription } from 'rxjs/Subscription';
// ...
private onDataChangeSubscription: Subscription;
constructor(public mySharedService: MySharedService) {
this.onDataChangeSubscription = mySharedService.onDataChange.subscribe(
updatedData => {
// You can use the updatedData to update the view
// ...
});
}
// Clean up the subscription when the page is about to be destroyed
ionViewWillUnload() {
this.onDataChangeSubscription.unsubscribe();
}
从任何其他页面更新数据时,您也需要使用共享服务:
constructor(public mySharedService: MySharedService) {}
yourMethod(): void {
// Your custom logic...
// ...
// Now you can publish the event to update the root page (and any other page subscribed to this event)
this.mySharedService.publishUpdate(updatedData);
}
如果您需要在每次更新数据时执行一些自定义逻辑,这种方法可能会更好,因此您可以在共享服务中执行此操作,然后广播结果,而不是对每个订阅者执行此操作...