如何在数据准备好后关闭Loader [英] How to dismiss Loader after data is ready

查看:91
本文介绍了如何在数据准备好后关闭Loader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 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()是进行服务调用的方法。
我该如何解决这个问题?这是实现加载器的正确方法吗?

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆