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

Get data async before a `Page` gets rendered

本文关键字:异步 获取 数据 页面      更新时间:2024-05-18

在渲染Page之前,获得数据异步的正确方法是什么?

据我所知,Angular2建议使用@CanActivate装饰器。遗憾的是,这对Ionic2不起作用,至少对我和其他来说不起作用

显然,Ionic2@CanActivate装饰器做了一些操作,请参见但它没有记录在案,我也不知道它到底做了什么。

然而,这家伙指出,由于离子缓存,无论如何都应该使用Ionics View States。他的例子如下:

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

这看起来像是他希望Ionic考虑返回的承诺,但快速浏览Ionics的消息来源会发现(至少我认为是这样)返回的值被忽略了。因此,不能保证promise在页面呈现之前得到解决。以下是onPage*的一个示例,以及它如何不能按需要/预期执行。

所以我很困惑,一个人是如何完成这项简单的任务的?

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

*edit:添加了反面示例

对于任何在使用Ionic 2时就限制页面访问对Stackoverflow进行爬网的人来说,Ionic建议使用的生命周期事件似乎是ionViewCanEnter

来自文档:

ionViewCanEnter在视图进入之前运行。这可以在经过身份验证的视图中用作一种"保护",您需要在视图进入之前检查权限。

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

我不确定这是否是的官方方式,但我在这种情况下使用Loading组件。您可以在Ionic API文档中找到更多信息。

页面.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()方法隐藏它。

你可以在这里找到一个工作的plunker(使用beta.9)

如果您只从一个位置导航到该页面,难道不能在导航并使用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;
        }
    }