이것은 공장 코드입니다. 콜백은 비동기이므로 $ rootScope.safeApply() 아래에 넣습니다. 그렇다면 내 컨트롤러에서 console.log (authService.authUser)를 호출하지만 사용자가 로그인 할 때 여전히 정의되지 않은 값을 반환합니다.하지만 사용자가 로그인하지 않으면 콘솔에 '로그인하지 않음'이 표시됩니다. 어떤 생각?
myapp.factory('authService', ['$rootScope', function($rootScope) {
var auth = {};
$rootScope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
auth.firebaseAuthClient = new FirebaseAuthClient(FIREBASEREF, function(error, user) {
$rootScope.safeApply(function() {
if (user) {
auth.authUser = user;
//auth.isLoggedIn = true;
} else if (error) {
auth.authError = error;
} else {
auth.not = 'not login';
//auth.isLoggedIn = false;
}
});
});
auth.login = function() {
this.firebaseAuthClient.login('facebook');
};
auth.logout = function() {
this.firebaseAuthClient.logout();
};
return auth;
}]);
2
이제 모든 일이 잘 작동, 나는 모니터링 사용자 로그인 상태로 할 수있어 컨트롤러
callback().then(function(response) {
$scope.isLoggedIn = true;
}, function(response) {
$scope.isLoggedIn = false //How can i set false here?
});
UPDATE에
auth.callback = function(error, user) {
if (user) {
deferred.resolve(user);
} else if (error) {
deferred.reject(error);
} else {
//deferred.reject('not login'); // there is no callback value here
}
return deferred.promise;
}
업데이트되었습니다. 하지만 여전히 문제가 있습니다. 아래 코드를 확인하십시오
authService.callback().then(function(success){
$rootScope.isLoggedIn = true; //If promise return success set isLoggedIn true
}, function(fail){
**//If user not login set isLoggedIn false;
//I have problem here because i'm not able to deferred.reject below**
$rootScope.isLoggedIn = false;
})
auth.callback = function(error, user) {
$timeout(function() {
if (user) {
deferred.resolve(user);
} else if (error) {
deferred.reject(error);
} else {
//If this line is added,
//.then() will not return anything not even undefined with no error,
//No mater user logged-in or not login.
//If I comment it out, everything will work fine but how can I
//set isLoggedIn = false?
deferred.reject();
}
}, 0);
return deferred.promise;
}
사용하는 대신 그 해키 safeApply 물건 약속드립니다. http://docs.angularjs.org/api/ng.$q – Oliver
@ OlivérKovács 안녕하세요, $ q ..를 사용하여 제 질문을 업데이트했습니다. 다시 확인해보십시오. – vzhen