![](/img/trans.png)
[英]How can I connect my ionic app to two different API URLS in the same page? how to pass the id from the first url's data to the second url?
[英]How can I pass data back to my root page in Ionic 2?
我有一个Ionic 2应用程序。 该应用程序的前提是上课。 打开一个类后,用户将被标记为在远程API中使用此类。
数据流是:
NavController.push(Page, { 'classes': classObjFromApi });
打开一个新视图NavController.push(Page, { 'classes': classObjFromApi });
。 classes
对象。 NavController.popToRoot()
导航回根目录 在根页面上显示每个类的状态('未启动','正在进行','已完成')。 在上面的流程中的第5点,用户被带回到根目录,但是它具有最初构建时的数据,这表示该类为“未启动”,即使它现在已经“完成”。
如何从堆栈中的其他页面更新根页面上的数据? 我曾假设popToRoot()
会接受navParams
因此我可以检查根页中是否存在该数据,如果存在则使用它,否则请求API。
我可以通过在ionViewDidEnter
方法上从API重新请求数据来解决这个问题,但这意味着每次用户查看此页面时都会发出API / HTTP请求,即使应用程序有数据也是如此。 看起来很乱。
如果我能帮助它,我宁愿不使用内部存储,因为它在加载页面时会产生延迟,因为我必须等待数据在显示之前从存储中提取。
所以我的问题是:最好的方法是什么? 如果要将数据传递给视图,如果popToRoot()
不支持nav params,我该怎么做?
最好的方法是使用事件 :
在您的根页面中,订阅自定义事件,以便在每次发布该事件时执行一些代码:
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非常相似,但在这种情况下,您需要添加共享服务,然后在更新数据时使用它。 我更喜欢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);
}
如果您需要在每次更新数据时执行一些自定义逻辑,这种方法可能会更好,因此您可以在共享服务中执行此操作,然后广播结果,而不是在每个订阅服务器上执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.