Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 (Ionic 2) call a function in a page when ever page is displayed

When ever my home page in angular 2(ionic 2) app is loaded I want call service/function. How to achieve this?

For the first time when the app is loaded(home page is loaded) I can write this in the constructor, but when user start using the app and push new pages into nav controller and pop them to come back to home page, the constructor wont get called again.

I am stuck here.

I would like to know what is the best way to achieve this feature?

I am new to angular2 and ionic2 framework (also don't have experiences in angular1 and ionic1), please help me out.

Many Many Thanks.

update

sample code of what I tried, but didn't worked.

import {Page, NavController, Platform, Storage, SqlStorage} from 'ionic-angular';

@Page({
  templateUrl: 'build/pages/page1/page1.html'
})
export class Page1 {
    static get parameters(){
        return [[NavController],[Platform]];
    }
    ngOnInit() {
        console.log("Showing the first page!");
    }
    constructor(nav, platform){
        this.nav = nav;
        this.platform =  platform;
    }
}
like image 288
Dipak Avatar asked Mar 19 '16 06:03

Dipak


2 Answers

onPageWillEnter() worked for me.

import {Page, NavController, Platform, Storage, SqlStorage} from 'ionic-angular';


@Page({
  templateUrl: 'build/pages/page1/page1.html'
})
export class Page1 {
    static get parameters(){
        return [[NavController],[Platform]];
    }
    onPageWillEnter() {
        console.log("Showing the first page!");
    }
    constructor(nav, platform){
        this.nav = nav;
        this.platform =  platform;
    }
}

Ionic lifecycle hook

like image 59
Dipak Avatar answered Nov 20 '22 09:11

Dipak


IONIC 2 RC1 Update

ionViewWillEnter() {
    console.log("this function will be called every time you enter the view");
}
like image 6
Romanow Avatar answered Nov 20 '22 08:11

Romanow