2013-06-06 2 views
0

이것은 공장 코드입니다. 콜백은 비동기이므로 $ 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; 
} 
+0

사용하는 대신 그 해키 safeApply 물건 약속드립니다. http://docs.angularjs.org/api/ng.$q – Oliver

+0

@ OlivérKovács 안녕하세요, $ q ..를 사용하여 제 질문을 업데이트했습니다. 다시 확인해보십시오. – vzhen

답변

0

외부 서비스의 지연 해결을 $ timeout 블록으로 감싸면 해결 된 시점을 알 수 있습니다. 컨트롤러가 콜백을 실행하면 $ digest주기가됩니다.

개념의 작업 증거로이 바이올린을 참조하십시오 : http://jsfiddle.net/Zmetser/rkJKt/

// in controller 
authService.login().then(success, error); 

// service 
myapp.factory('authService', ['$q', '$timeout', function($q, $timeout) { 
    var auth = {}, 
     deferred; 

    firebaseAuthClient = new FirebaseAuthClient(FIREBASEREF, afterAuth); 

    function afterAuth(error, user) { 
     // Let angular know the deferred has been resolved. 
     $timeout(function() { 
      if (user) { 
       deferred.resolve(user); 
      } else if (error) { 
       deferred.reject(error); 
      } else { 
       deferred.reject(); // there is no callback value here 
      } 
     }, 0); 
    } 

    auth.login = function() { 
     deferred = $q.defer(); 
     firebaseAuthClient.login('facebook'); 

     return deferred.promise; 
    }; 

    auth.logout = function() { 
     deferred = $q.defer(); 
     firebaseAuthClient.logout(); 

     return deferred.promise; 
    }; 

    return auth; 
}]); 
+0

감사합니다.하지만'afterAuth()'를 독립 실행 형으로 설정하려면 어떻게해야합니까? '.login ('facebook')' – vzhen

+0

기본적으로 모든 루트에 사용자가 로그인했는지 확인하고 싶습니다. – vzhen

+0

AfterAuth가 콜백입니다. 독립 실행 형이 어떻게 필요합니까? 사용자가 로그인하면 원하는 경우 상태를 서비스에 저장하거나 서버에서 가져옵니다. auth.loggedIn() – Oliver

관련 문제