Ionic 2 - 是否可以使用 poptoRoot 函数为 navParams?



我想知道是否可以使用 poptoRoot 函数为 navParams。他们在这里讨论的内容对我不起作用。有什么解决方法吗?要在 poptoRoot 页面和当前页面之间共享数据?

恐怕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();
}
}

最新更新