atx*_*atx 15 javascript typescript ionic2 ionic3 angular
Page
在呈现之前获取数据异步的正确方法是什么?
Angular2
@CanActivate
据我所知,建议装饰者.可悲的是,这不适用于Ionic2,至少不适合我和其他人
显然Ionic2
是与@CanActivate
装饰者做了一些事情,
但是看来它没有记录,我无法弄清楚它究竟做了什么.
然而,由于离子学缓存,这个人指出应该Ionics View States
反正使用.他的例子如下:
onPageWillEnter() {
return this._service.getComments().then(data => this.comments = data);
}
Run Code Online (Sandbox Code Playgroud)
看起来他期待Ionic考虑返回的承诺,但是快速浏览一下 Ionics消息来源(至少我认为是这样)会忽略返回的值.因此,无法保证在呈现页面之前解析promise .这是onPage*的示例,以及它如何根据需要/预期执行.
所以我迷路了,一个人如何完成这个简单的任务呢?
在第一个链接中,建议在导航到页面之前解析数据,这会增加被调用者页面所需数据的知识.在我看来,这不是一个选项.
*编辑:添加负面示例
对于任何在使用Ionic 2时抓取Stackoverflow 限制页面访问权限的人来说,它看起来像是Ionic推荐的生命周期事件ionViewCanEnter
.
来自文档:
ionViewCanEnter在视图可以进入之前运行.这可以在经过身份验证的视图中用作一种"保护",您需要在视图可以进入之前检查权限.
http://ionicframework.com/docs/v2/api/navigation/NavController/
我不确定这是否是官方的方法,但是我将这个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();
}
}
Run Code Online (Sandbox Code Playgroud)
代码非常简单,因此它不需要进一步的细节,我们的想法是定义一个,loading
以便我们可以显示它,然后尝试获取信息,一旦我们获得了这些数据,我们就可以隐藏它调用this.loading.dismiss()
方法.
你可以在这里找到一个工作的plunker(使用beta.9)
归档时间: |
|
查看次数: |
4323 次 |
最近记录: |