Cannot read property 'navCtrl' of undefined

前端 未结 2 472
醉梦人生
醉梦人生 2020-12-11 21:13

For hours I\'ve been searching for a solution to this problem in my project to no avail. I\'ve read many of the other \"Cannot read property ... of undefined\" posts, but ca

相关标签:
2条回答
  • 2020-12-11 21:54

    try like the below code:

    let _this;
    
    @Component({
      selector: 'page-signin',
      templateUrl: 'signin.html',
    })
    
    export class SignInPage {
    
      constructor(public navCtrl: NavController, public params: NavParams) {
        _this = this; //Either here or in onSignIn whichever called first
      }
    
      onSignIn() {
        _this = this; //Either here or in constructor whichever called first
        firebase.auth().signInWithPopup(provider).then(function(result) {
          console.log(result.credential.accessToken);
          console.log(result.user.displayName);
          _this.navCtrl.setRoot(HomePage);
        }).catch(function(error) {
          console.log(error.message);
        });
      }
    }
    

    I think you are facing the problem because of the scope of this. In your case scope of this belongs to the function which is passed inside then.

    0 讨论(0)
  • 2020-12-11 22:10

    A better way to solve this issue would be by using arrow functions:

    An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.

    So your issue would be solved by just changing the onSignIn method like this:

      onSignIn() {
        firebase.auth().signInWithPopup(provider).then((result) => {
          console.log(result.credential.accessToken);
          console.log(result.user.displayName);
          this.navCtrl.setRoot(HomePage);
        }).catch(function(error) {
          console.log(error.message);
        });
      }
    

    Notice the (result) => {...} instead of the function(result) {...}

    0 讨论(0)
提交回复
热议问题