angular – 如何在数据准备好后关闭Loader

在我的Ionic 2应用程序中,我有一个消耗服务的组件,该服务使http GET获取一些数据.然后我的组件调用此服务,当数据可用时,它会设置并显示它.

它看起来如下:

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)

  }
...

}

当我的组件异步提取数据时,我试图让一个加载器旋转,一旦数据可用,我希望加载器消失.

但是,使用我当前的代码,即使数据可用并显示,微调器也会继续旋转,如屏幕截图所示:

getData()是进行服务调用方法.
我怎样才能解决这个问题?这是实现加载器的正确方法吗?

你可以找到一个 working plunker here.

就像你可以在那个plunker的代码中看到的那样,我会做一些更改,以使你的代码正常工作:

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)changelog发布:

onPageWillEnter已重命名为ionViewWillEnter

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...