0

I have the following error with my code:

Cannot read property 'setRoot' of undefined

When setTimeout() is removed, the code works fine. I can't understand why this is happening though nav is properly defined.

export class LoginStudentPage {

  constructor(public nav: NavController, public loadingCtrl: LoadingController) {
    this.loading = this.loadingCtrl.create();
  }

  loading: any;

  goToDiary(child){
      this.storage.set('regNo', child);
      this.loading.present();
      setTimeout(function(){
        this.nav.setRoot(TabsNavigationPage);
        this.loading.dismiss();
      }, 1500);
  }
}
Melchia
  • 16,699
  • 16
  • 70
  • 93
  • when the function goToDiary is called? – Ricardo Mar 01 '18 at 21:35
  • 3
    use an arrow function as the function you give to setTimeout so the same lexical context is kept and `this` works as you want it to – toskv Mar 01 '18 at 21:57
  • Thanks, it worked fine! But I still couldn't understand why it is so. Could you please explain more elaborately, @toskv –  Mar 02 '18 at 13:57
  • Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – toskv Mar 02 '18 at 14:16
  • @ShafeefOmar check out the duplicate question I linked. it's all about this. – toskv Mar 02 '18 at 14:16

1 Answers1

0

Inside your function this no longer refers to your class & refers instead to the object window. So one of the solutions to solve this issue is by using arrow functions.

goToDiary(child){
      this.storage.set('regNo', child);
      this.loading.present();
      setTimeout(_=> {
        this.nav.setRoot(TabsNavigationPage);
        this.loading.dismiss();
      }, 1500);
  }
Melchia
  • 16,699
  • 16
  • 70
  • 93