在我的 Ionic 2 应用程序中,我有一个使用服务的组件,该服务使 http GET 获取一些数据.然后我的组件调用此服务,当数据可用时,它会设置并呈现它.
In my Ionic 2 app, I have a component that consumes a service which makes an http GET to fetch some data. My component then calls this service and when data is available it sets and presents it.
如下所示:
export class FarmList implements OnInit { items: Object; constructor(public testService: TestService, public nav: NavController){ } ngOnInit(){ this.getData() } getData(){ let loading = Loading.create({ content: 'Please wait..', spinner: 'crescent' }) this.nav.present(loading) this.testService.fetchData().then(data => this.items = data) } ... }当我的组件异步获取数据时,我试图让 loader 旋转,一旦数据可用,我希望 loader 消失.
While my component fetches the data asynchronously, I am trying to have a loader spinning and once the data is available, I want the loader to disappear.
但是,使用我当前的代码,即使在数据可用并显示后,微调器也会继续旋转,如屏幕截图所示:
However, with my current code the spinner keeps spinning even after data is available and displayed as can be seen the screenshot:
getData() 是进行服务调用的方法.我该如何解决这个问题?实现loader的方式是否正确?
getData() is the method that makes service call. How can I fix this? Is it the correct way to implement loader?
推荐答案你可以找到一个 工作插件这里.
就像您在那个 plunker 的代码中看到的那样,我会进行一些更改以使您的代码正常工作:
Like you can see in the code of that plunker, I would make a few changes in order to make your code work properly:
export class FarmList implements OnInit { items: Object; // Define the loading var here, so we can access later when the information is ready loading : any; constructor(public testService: TestService, public nav: NavController){ } // Instead of 'ngOnInit', I would use 'ionViewWillEnter' ionViewWillEnter(){ this.getData() } getData(){ this.loading = Loading.create({ content: 'Please wait..', spinner: 'crescent' }) this.nav.present(this.loading) this.testService.fetchData().then(data => { this.items = data; // After we get the data, we hide the loading this.hideLoading()}); } // I 've added this method so we can grab the loading var and use it // to hide the loading component. private hideLoading(){ this.loading.dismiss(); } ... }=================================
================================
更新:
截至 Ionic 2.0.0-beta.8 (2016-06-06) 变更日志:
As of the release of Ionic 2.0.0-beta.8 (2016-06-06) changelog:
onPageWillEnter 已重命名为 ionViewWillEnter
更多推荐
数据准备好后如何关闭 Loader
发布评论