在呈现“页面”之前获取数据异步

Get data async before a `Page` gets rendered

在呈现 Page 之前获取数据异步的正确方法是什么?

据我所知,

Angular2 建议使用 @CanActivate 装饰器。遗憾的是,这不适用于 Ionic2,至少对我和 others

无效

显然 Ionic2@CanActivate 装饰器做了一些事情,see 但它没有记录,我无法弄清楚它到底做了什么。

尽管如此,this guy 指出无论如何都应该使用 Ionics View States,因为离子缓存。他的示例如下所示:

  onPageWillEnter() { 
      return this._service.getComments().then(data => this.comments = data);
  }

看起来他希望 Ionic 考虑返回的承诺,但是 quick glance a Ionics sources reveals (at least I think so) that the returned value is ignored. Hence there is no guarantee that the promise gets resolved before the page gets rendered. Here is an example 和 onPage* 以及它如何不执行 needed/expected。

所以我迷路了,如何完成这个简单的任务?

在第一个link中,建议在导航到页面之前先解析数据,这会给被调用者增加页面需要哪些数据的负担。我认为这不是一个选择。

*编辑:添加反例

如果您只从一个位置导航到该页面,难道不能在导航之前简单地加载数据并使用 NavParams 传递数据吗?

我将此结构用于个人资料页面,从某个索引页面我单击用户,然后在访问他的个人资料之前检索他的个人资料。发生这种情况时,您可以表现得很好 Loading

let self=this;
this.profileSvc.getProfile(id)
.then(profile => {
    self.nav.push(Profile, {profile:profile});
});

现在在个人资料页面中,您可以使用 NavParams 来初始化您的页面。

export class Profile {
    profile:any;
    constructor(private params:NavParams) {
        if(params.get('profile')) {
            this.profile = params.get('profile');
        } else {
            this.profile = this.me;
        }
    }

我不确定这是否是官方方式,但我在这种情况下使用Loading组件。您可以在 Ionic API Docs.

中找到更多信息

页面 .ts 文件如下所示:

import {Component} from '@angular/core';
import {Loading, NavController} from 'ionic-angular';

@Component({
  templateUrl:"page1.html"
})
export class Page1 {
  // Loading component
  loading : any;
  // Information to obtain from server
  comments: string = '';

  constructor(nav: NavController) {
    this.nav = nav;
  }

  onPageWillEnter() {
    // Starts the process 
    this.showLoading();
  }

  private showLoading() {
    this.loading = Loading.create({
      content: "Please wait..."
    });
    // Show the loading page
    this.nav.present(this.loading);
    // Get the Async information 
    this.getAsyncData();
  }

  private getAsyncData() {

    // this simulates an async method like
    // this._service.getComments().then((data) => { 
    //     this.comments = data);
    //     this.hideLoading();
    // });

    setTimeout(() => {
      // This would be the part of the code inside the => {...}
      this.comments = "Data retrieved from server";
      // Hide the loading page
      this.hideLoading();
    }, 5000);
  }

  private hideLoading(){
    // Hide the loading component
    this.loading.dismiss();
  }
}

代码很简单所以不需要更多的细节,想法是定义一个loading所以我们可以显示它,然后尝试获取信息,一旦我们得到它数据,我们可以调用 this.loading.dismiss() 方法隐藏它。

您可以找到 working plunker here(使用 beta.9)

对于在使用 Ionic 2 时 限制 页面访问的任何爬取 Whosebug 的人来说,看起来 Ionic 推荐的生命周期事件是 ionViewCanEnter

来自文档:

ionViewCanEnter Runs before the view can enter. This can be used as a sort of "guard" in authenticated views where you need to check permissions before the view can enter.

http://ionicframework.com/docs/v2/api/navigation/NavController/