2013-06-21 1 views
1

나는 anglejs에 다음 코드를 가지고 있습니다 .run() 그래서 앱이 초기 상태 일 때 rootscope 아래에 2 개의 변수를 설정했습니다. 이 녀석들은 모든 루트 (페이지)와 컨트롤러에서 사용하기로 결정했기 때문입니다. 내 컨트롤러에서 실행할 때 비동기다른 컨트롤러에서 angularjs 초기화 된 변수를 재사용하는 방법

app.run(function($rootScope, $timeout, firebaseAuth) { 
    $rootScope.$on('firebaseLoggedIn', function(event, authUser) { 
    $timeout(function() { 
     $rootScope._isLoggedIn = true; 
     $rootScope._authUser = authUser; 
    },0); 
}); 

그러나 여기에서 문제는 항상 정의되지 않은 보여줍니다. 을 기능 블록에 넣지 않는 한. 그래서 제 생각 엔 컨트롤러가 실행되고 있습니다 .run() 이전에 가있었습니다.

app.controller('foo', function($scope){ 
    console.log($scope._authUser); //Always undefined 

    //unless I do following 
    //$scope.clickme = function() {console.log($scope._authUser)}; 
}); 

제안 사항 .run()에서 vars (async)를 사용할 수 있습니까?

모든 컨트롤러에서 다음 코드를 호출하면 반복되는 것처럼 보입니다.

$rootScope.$on('firebaseLoggedIn', function(event, authUser) {}); 

UPDATE 여기서 여기서 firebaseLoggedIn 이벤트이다. 나는 다시 언급해야한다고 생각한다. 콜백은 비동기입니다.

app.service('firebaseAuth', ['$rootScope', 
function($rootScope) { 
    //Define firebase DB url 
    this.firebaseRef = new Firebase("https://test.firebaseio.com"); 
    this.onLoginStateChanges = new FirebaseAuthClient(this.firebaseRef, function(error, user) { 
     if (user) { 
      $rootScope.$emit("firebaseLoggedIn", user); //authenticated user 
     } 
     else if (error) { 
      $rootScope.$emit("firebaseLoginError", error); //authentication failed 
     } 
     else { 
      $rootScope.$emit("firebaseLogout"); //user not login 
     } 
    }); 
}]); 

답변

0

주사기가 앱의 모든 모듈을로드하면 실행 방법이 실행됩니다. 따라서 컨트롤러가 처음 인스턴스화된다는 가정은 사실입니다.

$ timeout (function() {...}, 0)을 효과적으로 사용하면 코드가 다음 다이제스트 루프에서 실행됩니다. 그러나 나는 이것이 당신이 어쨌든 성취하려고 시도하는 것이라고 생각하지 않습니다.

'firebaseLoggedIn'이 (가) 어디에서 방송되고 있는지 확실하지 않습니다. 그러나이 전체 구현이 각도 서비스보다 더 직선적 인 것을 알 수 있습니다. 컨트롤러에서 다음

app.service('FireBaseService', function($rootScope) { 
    // store these inside the service to be retrieved via methods below. 
    var isLoggedIn = false; 
    var authUser = {}; 

    // let this be the only place you handle the LoggedIn event, setting user context. 
    $rootScope.$on('firebaseLoggedIn', function(event, authUser) { 
     isLoggedIn = true; 
     authUser = authUser; 
    }); 

    // return some functions to expose the variables above 
    return { 
     getIsLoggedIn: function() { 
     return isLoggedIn; 
     }, 
     getAuthUser: function() { 
     return authUser; 
     } 
    } 
}); 

는 ......

app.controller('foo', function($scope, $log, FireBaseService){ 
    if (FireBaseService.getIsLoggedIn()){ 
     $log.info(FireBaseService.getAuthUser().Name); 
    } 
}); 

이것은 어디서든 당신이 FireBaseService 서비스를 주입 한 이러한 변수에 액세스 할 수 있습니다.

+0

시도했지만 작동하지 않습니다. 컨트롤러에서'FirebaseService.getIsLoggedIn()'은 false를 반환합니다. firebaseLoggedIn 이벤트를 수신하지 않기 때문에 나는 생각한다. 내 질문을 다시 확인하십시오. 그것을 업데이트했습니다 – vzhen

+0

$ rootScope를 변경하십시오. $ emit을 $ rootScope. $ broadcast로 변경하십시오. $ emit은 범위를 통해 위쪽으로 이벤트를 디스패치하기위한 것이고, 아래쪽은 $ broadcast입니다. –

+0

운이 없으면 false도 반환하십시오. – vzhen

관련 문제