原文: https://medium.com/@paulstelzer/ionic-4-and-the-lifecycle-hooks-4fe9eabb2864

--------------------------------------------------------------------------------------------

There are a lot of questions related to Ionic 4 and the Lifecycle Hooks. There are new issues at the Ionic Github Repository where people complain that the Lifecycle Hooks are not working. So I will tell you in this article when the Lifecycle Hooks are running in Ionic 4.

For example:

When I navigate from the home to another route, the lifecycle ngOnDestroy of the home component is not executed

But why? Let’s start how Lifecycle Hooks working in Ionic 4!

TL;DR

Please skip to the end of the page, I added a short summary ;)

Ionic 4 uses the Angular Lifecycle Hooks

The first good news: Ionic 4 uses the Angular Lifecycle Hooks! So you can use ngOnInit, ngOnDestroy and all other Lifecycle hooks and do not have to remember the special ones from Ionic. Read more about Angular Lifecycle Hooks at the official documentation!

Short recap: How it was in Ionic 3

If you already used Ionic 3, then you will used ionViewDidLoadionViewWillEnterand ionViewDidEnteron pushing a new view and if the current view pops away you use ionViewWillLeaveionViewDidLeaveand ionViewWillUnload. Also two nav guards ( ionViewCanEnter and ionViewCanLeave) . At the Ionic Blog you find a very good post about it and the following image which shows the lifecycles very good:

 

Ionic 3 lifecycle — Source: blog.ionicframework.com

Are these lifecycles still working?

Yes, Ionic has still this lifecycles (see in Github). Only ionViewDidLoad has been replaced with Angular Lifecycle (use ngOnInit now).

Also the two nav guards ( ionViewCanEnter and ionViewCanLeave) were removed because Angular Router provides route guards, so you can determine if a user can access a route and can leave a route ( canActivate and canDeactivate ). ionViewWillUnloadis not required if you use Angular, here you have to use ngOnDestroy . But Ionic 4 is framework independent, so in other cases this can be useful. ionViewWillEnterionViewDidEnterionViewWillLeaveand ionViewDidLeave are still very nice, but more about it later!

Ionic 4 and ion-router-outlet

If you already created a sample app like the blank starter, tabs starter, or sidemenu starter, you will notice the <ion-router-outlet></ion-router-outlet> instead of <router-outlet></router-outlet> in your app.component.html and a

{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }

in your app.module.ts.

You can still use <router-outlet></router-outlet> with the Ionic 4 components, but the Ionic team added a special feature to it:

A “stack” functionality like in Ionic 3

Okay! And what does this mean?

Normally if you switch from one route to another in Angular, the components will be destroyed immediately. The Ionic router keeps the components (Ionic calls it pages — I like this terminology) in a stack. They are not destroyed by default.

Show me in practice

Enough theory, let’s see how it works in practice. I created a new project based on the starter package of Ionic and created two new pages: ListPage and ListItemPage. ListPage contains a list of items and if I tap on a item, I will redirect to the ListItemPage.

 

Lifecycle in Ionic 4

The GIF above shows a lot of details, so I will guide you through it:

  1. We start on ListPage and I tap on a item, so I will navigate to the ListItemPage (I navigate forward). Take a look at the console: No ngOnDestroy! But this is not a bug!

Here is the source code. I am using NavController from Ionic (navigateForward() is the same like router.navigate() )

gotoItem() {
// navController is instanceof NavController from '@ionic/angular'
// the following is the same like this.router.navigate()
this.navController.navigateForward(['/list-item']);
}

2. I am on ListItemPage now! I am using the <ion-back-button>, but you can also use navController.navigateBack(url). If I tap on the back button, you see ‘ngOnDestroy ListItem’ in the console.

3. If I take a look at the inspector and see the elements, you see the stack functionality. The ListPage is still in our DOM, it’s not visible because it’s behind the ListItemPage. If I navigate backward, the ListItemPage will be destroyed (removed from the stack — also removed from DOM).

In short: Whenever you wonder, why ngOnDestroy is not firing, just take a look at the DOM inspector and you will see that the component is still there. It’s not destroyed yet, so ngOnDestroy is not firing!

Earlier I talked about the special Ionic Lifecycles. We can use them here now! If you leave ListPage and want to cancel the observables, just do it inside ionViewWillLeave or ionViewDidLeave. If the component becomes active again, just subscribe to that observable inside ionViewWillEnteror ionViewDidEnter. Everything in ngOnInit will not be triggered because the component was already initialized.

And when I want to destroy ListPage ?

If you do not want to push ListPage into the stack, just use navigateRoot() of the NavController!

gotoItem() {
this.navController.navigateRoot(['/list-item']);
}

If you execute this now, ngOnDestroy will be triggered, the component will be removed from DOM. It’s not added to the stack.

And what about ion-tabs?

At the moment (beta.15) ion-tabs are only lazy loading at the beginning. Open a tab initialize the component. If you now switch to another tab, this will be initialize at the first time. If you move back to the last tab, you will not see any Lifecycle hooks (neither ngOnInit nor ionViewWillEnter ).

If you remove the TabsPage from the Stack (for example by navigateRoot() to another route), all components will be destroyed at once. Then you will see the ngOnDestroy lifecycle hook.

Maybe the lifecycle of tabs change in future, but for now this is the behaviour. You can take a look at this issue at GitHub to follow that process.

Summary: Lifecycles in Ionic 4

Okay Paul, nice background information, but what should I memorize?

  1. Ionic 4 extends the Router Navigation of Angular
  2. Ionic 4 introduces a stack functionality (like in Ionic 3)
  3. Ionic 4 adds new Lifecycle Hooks to Angular: 
    ionViewWillEnter — Fired when entering a page (also if it’s come back from stack)
    ionViewDidEnter — Fired after entering (also if it’s come back from stack)
    ionViewWillLeave — Fired if the page will leaved (also if it’s keep in stack)
    ionViewDidLeave — Fired after the page was leaved (also if it’s keep in stack)
    ionViewWillUnload — In Angular not firing because here you have to use ngOnDestroy
  4. Except ionViewDidLoad (because it’s the same like ngOnInit) and the two nav guards all Lifecycle hooks from Ionic 3 are still available
  5. ngOnInit will not be triggered, if you come back to a page after putting it into a stack
  6. By default, if you navigate forward, the current page keeps in stack, so NOngOnDestroy will be triggered. Only if you set the new page as root (navController.navigateRoot())) or you navigate backwards, it will be removed from stack
  7. If you want to cancel Observables, just do it ionViewWillLeave or ionViewDidLeave and subscribe to it again in ionViewWillEnter or ionViewDidEnter
  8. Take a look at the DOM inspector, there you can see that your page is still in the stack
  9. If you use the Angular Router, pages will add to the stack. I recommend to use the Ionic Angular NavController because here you can use the new stack functionality
  10. At the moment (beta.15) If you use ion-tabs, a tab will be initialized if you open it the first time and then stay active all time (it will not be removed nor any lifecycle hooks will be triggered if you switch back — see this issue at Github)

Do you have more questions or I write something not correctly, just let me know and post a comment!

Ionic 4 and the Lifecycle Hooks的更多相关文章

  1. [Recompose] Add Lifecycle Hooks to a Functional Stateless Component using Recompose

    Learn how to use the 'lifecycle' higher-order component to conveniently use hooks without using a cl ...

  2. Kubernetes Container lifecycle hooks

    简介 在kubernetes中,容器hooks旨在解决服务进程启动与停止时的一些优雅操作需求.比如说进程停止时要给进程一个清理数据的时间,保证服务的请求正常结束,而不是强行中断服务的运行,这样在生产环 ...

  3. [MST] Use Volatile State and Lifecycle Methods to Manage Private State

    MST has a pretty unique feature: It allows you to capture private state on models, and manage this s ...

  4. kubernetes concepts -- Pod Lifecycle

    Pod Lifecycle This page describes the lifecycle of a Pod. Pod phase A Pod’s status field is a PodSta ...

  5. Vue.js学习笔记(1)

    数据的双向绑定(ES6写法) 效果: 没有改变 input 框里面的值时

  6. Vue.js:轻量高效的前端组件化方案

    转发一篇尤老师对vue.js的介绍,了解vue.js的来龙去脉.不过现在已经是2.0了,也有添加一些新的东西,当然有些东西也改了. Vue.js:轻量高效的前端组件化方案 Vue.js 是我在2014 ...

  7. 各种报错各种坑 webpack让我在学习的过程中一度想要放弃

    由于拓展部分不是必须的,只是可以增强用户体验,但是有些时候页面给分页预留的位置不够,这个时候我们就可以通过设置来除去这一部分 子分区由两种创建方法,一种是不定义每个子分区子分区的名字和路径由分区决定, ...

  8. vue.js慢速入门(2)

    4.组件使用基础 什么是组件?组件可以理解为可重用的自定义HTML. 可以使用一堆组件来构造大型应用,任意类型的应用界面都可以抽象为一个组件树: 可以把组件代码按照template.style.scr ...

  9. Vue.js:轻量高效的前端组件化方案(转载)

    摘要:Vue.js通过简洁的API提供高效的数据绑定和灵活的组件系统.在前端纷繁复杂的生态中,Vue.js有幸受到一定程度的关注,目前在GitHub上已经有5000+的star.本文将从各方面对Vue ...

随机推荐

  1. web服务端安全之文件上传漏洞

    一.文件上传漏洞的原理 由于程序代码未对用户提交的文件进行严格的分析和检查,导致攻击者可以上传可执行的代码文件,从而获取web应用的控制权限. 常见于上传功能,富文本编辑器. 二.文件上传漏洞的防御 ...

  2. [ 原创 ] Java基础1--Java中super和this的用法和区别

    许多同学在学习Java时分不清楚this和super的用法和区别,今天偶然发现一片加精的博文,看完内容准备自己也写下来积累一下 1.如果想在子类的构造方法中调用父类的构造方法,必须在子类的构造方法中使 ...

  3. scrapy爬虫,爬取图片

    一.scrapy的安装: 本文基于Anacoda3, Anacoda2和3如何同时安装? 将Anacoda3安装在C:\ProgramData\Anaconda2\envs文件夹中即可. 如何用con ...

  4. wpf企业应用之数据校验

    wpf中使用IDataErrorInfo实现数据校验,绑定实体需要实现了此接口,并在UI绑定表达式中添加ValidatesOnDataErrors=True,这样数据校验发生时,wpf会调用该接口中的 ...

  5. CF961E Tufurama 主席树

    对原问题进行转化 考虑对每个$i$,询问在$j \in [i + 1, a[i]]$中满足$a[j] \geqslant i$的个数 这样子可以做到不重不漏 个数满足差分的性质,使用主席树来维护即可 ...

  6. 【SPFA判断负环】BZOJ1715- [Usaco2006 Dec]Wormholes 虫洞

    [题目大意] 判断一张图中是否存在负环. [思路] dfs版SPFA. #include<bits/stdc++.h> using namespace std; struct edge { ...

  7. bzoj 3240 矩阵乘法+十进制快速幂

    首先,构造出从f[][i]->f[][i+1]的转移矩阵a,和从f[i][m]->f[i+1][1]的转移矩阵b, 那么从f[1][1]转移到f[n][m]就是init*(a^(m-1)* ...

  8. Mysql的学习随笔day1

    关于mysql的基本语句 ps:[]是缺省 创建:CREATE DATABASE  db.name CREATE TABLE name(列名,类型,[NULL])NOT NULL是不需要为空,NOT ...

  9. python开发_xml.dom_解析XML文档_完整版_博主推荐

    在阅读之前,你需要了解一些xml.dom的一些理论知识,在这里你可以对xml.dom有一定的了解,如果你阅读完之后. 下面是我做的demo 运行效果: 解析的XML文件位置:c:\\test\\hon ...

  10. ZOJ 3631 Watashi's BG DFS

    J - Watashi's BG Time Limit:3000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu Subm ...