How to detect when a user leaves a page in Ionic 2?

As the title says, how do you detect when a user leaves a view in Ionic 2?

Do you look something like an event onPageWillLeave ?

If so, you have some event here that could interest you. I never tested, but it worth to try

2 Likes

@Devniz the question relates to Ionic 2 so you cannot use $scope

2 Likes

@richardshergold Oops you are right about that, didn’t saw it was only for Ionic 2.

Yes, as @icarus_31 said, you can use the lifecycle hooks. The conference app has an example of disabling/enabling the menu here:

https://github.com/driftyco/ionic-conference-app/blob/master/app/pages/tutorial/tutorial.js#L54-L62

1 Like

Thank you so much @brandyshea . This is exactly what I was looking for.

1 Like

Hi @brandyshea what about exec a function and prevent or allow defaultBehavior accordingly for all pages?

Say i want to check if user is logged in for all pages except login page with the function this.conf.checkAccessToken and if access token exists then the page shows as requested, but if it doesn’t exist redirect to login page.

I’m currently calling the checkAccessToken() in each constructor, but this is a lot of boilerplate.

Jep, same here.
On every navigation, I want to check if the user has access rights and react appropriately.

So I have to implement onPageDidEnter in every Page class which is not very elegant.
One solution is using a super class which implements the logic, but this can cause boiler plate code due to DI:

class SecuredPage{
    constructor(private security: SecurityService){}
    onPageDidEnter(){
        //check security using security
    }
}

class MyPage extends SecuredPage{
    constructor(security: SecurityService){
        super(security);        
    }
}

MyPage must inject SecurityService even though it is not using it.

So, a global navigation listener which gets informed about every navigation change would make sense, I think.

Is there a way to use this to detect the user switching tabs? I wish to insert this.navCtrl.pop(); before the user switches tabs and onPagewillLeave() appears to not work in my code when just switching to a tab and back.

Thanks

John

same feature i want in my app. so got any solution ?

There is the ionChange event in ion-tabs:
ionChange - Emitted when the tab changes.
But I think it gets fired after the tab was changed.

You could get the NavController that the tabs are using and register on its viewWillLeave observable. But I am not sure if it will work for your use case.

Where do you see that?

I guess the original post has been edited in favor of the tutorial link