最好的方法是使用Events https://ionicframework.com/docs/api/util/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);
}
EDIT
另一种方法是使用共享服务,并使用Subject
发布/订阅更改。结果将非常类似于离子事件,但在这种情况下,您需要添加共享服务,然后在数据更新时使用它。我更喜欢 Ionic Events,但为了以防万一,您可以这样做:
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);
}
如果您需要在每次更新数据时执行一些自定义逻辑,那么这种方法可能会更好,因此您可以在共享服务中执行此操作,然后广播结果,而不是在每个订阅者上执行此操作...