16

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

Angular2@CanActivate据我了解,建议装饰师。可悲的是,这不适用于 Ionic2,至少不适用于我和其他人

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

尽管如此,这个家伙指出Ionics View States,由于离子缓存,无论如何都应该使用它。他的示例如下所示:

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

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

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

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

*编辑:添加反例

4

3 回答 3

9

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

从文档:

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

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

于 2016-10-23T17:04:53.780 回答
7

我不确定这是否是官方的做法,但我在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)

于 2016-06-24T13:08:58.997 回答
1

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

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

let self=this;
this.profileSvc.getProfile(id)
.then(profile => {
    self.nav.push(Profile, {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;
        }
    }
于 2016-05-19T11:47:46.553 回答