恐怕 popToRoot 只接受 NavOptions 类型的参数(与页面的过渡有关),因此您需要将数据发送回根页面:
您可以在根页面订阅该事件,然后在子页面中发布该事件,将数据作为该事件的一部分发送。
import { Events } from 'ionic-angular';
// Child page: publish the event sending the data
constructor(public events: Events) {}
someMethod(data) {
this.events.publish('data:modified', data);
}
// Root page: subscribe to the event to get the data
constructor(public events: Events) {
events.subscribe('data:modified', (data) => {
// Handle the data...
});
}
使用共享服务
如果您需要发送的参数是简单的数字或数组,您可以使用共享服务将数据存储在那里,以便根页面可以从服务中读取,子页面可以修改它从那里也是。
如果您需要在每次数据更改时执行一些逻辑,那么您可以像这样使用Subject:
@Injectable()
export class YourItemsService {
public onItemsChange: Subject<any> = new Subject<any>();
// ...
public changeItems(someParam: any): void {
// ...
// Send the new data to the subscribers
this.onItemsChange.next(newItems);
}
}
这样子页面可以使用服务更改数据,知道更改也会传播到所有订阅它的页面:
@Component({
selector: 'child-page',
templateUrl: 'child-page.html'
})
export class ChildPage {
constructor(private yourItemsService: YourItemsService) {}
updateItems(data: any) {
// Use the service to modify the data, keeping everyone updated
this.yourItemsService.changeItems(data);
}
}
并且根页面可以订阅数据的变化,每次变化时执行一些逻辑:
@Component({
selector: 'root-page',
templateUrl: 'root-page.html'
})
export class RootPage {
private itemsChangeSubscription: Subscription;
constructor(private yourItemsService: YourItemsService) {
// Subscribe to changes in the items
this.itemsChangeSubscription = this.yourItemsService.onItemsChange.subscribe(data => {
// Update the data of the page...
// ...
});
}
ionViewWillUnload() {
// Clear the itemsChangeSubscription
this.itemsChangeSubscription && this.itemsChangeSubscription.unsubscribe();
}
}