2017-05-10 2 views
1

다음 코드로 로그 아웃을 구현하려고 시도 할 때 TypeError: undefined is not an object (evaluating 'this.logOut')이 표시됩니다. 나는 또한 내가 현재 logOut 함수를 호출 한 곳의 내부에 logOut 함수의 내용을 넣으려고 시도했지만, 같은 것을 얻고있다. this 오류.사용자가 로그인하지 않은 경우 로그인으로 리디렉션 -

export class ContactPage { 

    user: any; 

    constructor(public navCtrl: NavController, public authData: AuthData) { 

    } 

    ionViewWillEnter() { 
    firebase.auth().onAuthStateChanged(function(user) { 
     if (!user) { 
     console.log("user is not logged in"); 
     this.logOut(); 
     } else { 
     console.log("user is logged in"); 
     return; 
     }  
    }); 
    } 

    logOut() { 
    this.authData.logoutUser().then(() => { 
     this.navCtrl.setRoot(Login); 
    }); 
    } 

} 

답변

1

귀하의 문제는 this이 (인해 다른 범위에) 콜백 다른 점이다. 범위를 수정하려면 생성자에서 함수를 바인딩하면됩니다.

constructor(public navCtrl: NavController, public authData: AuthData) { 
    // This line says that every time onAuthCallback is called, the 
    // value of 'this' in the function is the same as what it is here. 
    this.onAuthCallback = this.onAuthCallback.bind(this); 
} 

onAuthCallback(user) { 
    if (!user) { 
     console.log("user is not logged in"); 
     this.logOut(); 
    } else { 
     console.log("user is logged in"); 
     return; 
    }  
} 

ionViewWillEnter() { 
    // When the callback is triggered, it will have the 
    // proper value for 'this'. 
    firebase.auth().onAuthStateChanged(this.onAuthCallback); 
} 
관련 문제