Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOnInit not called when coming back

Tags:

angular

ionic2

I noticed that the ngOnInit() method gets not called when I come back to the page which is already instanced. I have to use any other method for this? I need a method which is called everytime when he is visiting the specific page.

EDIT Tested already onPageWillEnter() but it gets not fired in Ionic 2

like image 584
Sandruna Avatar asked Feb 22 '17 09:02

Sandruna


3 Answers

Check Lifecycle Events section in the link.

You can use ionic 2 lifecycle hook

ionViewWillEnter(){
 //your methods
}
like image 123
Suraj Rao Avatar answered Nov 16 '22 20:11

Suraj Rao


If you change a route so that only a parameter value changed, then the component is reused.

You can use

constructor(router:Router) {
  router.params.subscribe(val => myInit());
}

to call your initialization code instead of using ngOnInit() in such cases.

like image 28
Günter Zöchbauer Avatar answered Nov 16 '22 21:11

Günter Zöchbauer


To recall ngOnInit everytime when page is visiting, you should use ngOnDestroy. For example, if your component content depends on code in url, you should use OnDestroy, in this way:

export class GRMTasksComponent implements OnInit, OnDestroy {

   subParams: Subscription;

   ngOnInit() {
        this.subParams = this._route.params.subscribe(params => {
           //some code...
      });
   }

   ngOnDestroy() {
        this.subParams.unsubscribe();
   }
}
like image 4
Jaroslaw K. Avatar answered Nov 16 '22 20:11

Jaroslaw K.