离子 2 或离子 2+ 中的 ngOnInit 与 ionViewDidLoad [英] ngOnInit vs ionViewDidLoad in ionic 2 or ionic 2+

查看:11
本文介绍了离子 2 或离子 2+ 中的 ngOnInit 与 ionViewDidLoad的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用哪一个来初始化数据,为什么?

Which one will I use for initializing data and why?

ngOnInit() {
    this.type = 'category';
    this.getData();
    this.setData();
}

ionViewDidLoad() {
    this.type = 'category';
    this.getData();
    this.setData();
}

推荐答案

ngOnInit 是 Angular2 调用的生命周期钩子,表示 Angular 已完成创建组件.

ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.

ionViewDidLoad 与 Ionic 的 NavController 生命周期事件有关.它在页面加载后运行.这个事件在每个页面被创建时只发生一次.

ionViewDidLoad is related to the Ionic's NavController lifeCycle events. It runs when the page has loaded. This event only happens once per page being created.

基本上两者都是初始化组件数据的好地方.

Basically both are good places for initializing the component's data.

但是要使用 ngOnInit 你需要实现 Angular 的 OnInit 类,另一方面,ionViewDidLoad 只能为从 NavController 推送/弹出的组件定义.

But for using ngOnInit you need to implement the Angular's OnInit class, In the other hand ionViewDidLoad could be only defined for components that are pushed/popped from a NavController.

所以我会说 ionViewDidLoad 用于 NavController 堆栈中的组件, ngOnInit 用于其他组件.

So I would say use the ionViewDidLoad for components in the NavController stack and ngOnInit for other components.

这篇关于离子 2 或离子 2+ 中的 ngOnInit 与 ionViewDidLoad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆