2015-02-07 62 views
0

我试图在用户的uid中插入一些东西到我的Firebase数据库中,但出于某种原因未定义。看看下面的代码:

,设置该用户的数据信息(authData)主控制器在页面加载时:

flickrApp.controller('mainCtrl', ['$scope', '$rootScope', '$firebase', 'Auth', 'shared', function($scope, $rootScope, $firebase, Auth, shared) { 

    Auth.$onAuth(function(authData) { 
     shared.setAuth(authData); 
     $scope.authData = shared.getAuth(); 
    }); 
}]); 

它处理认证状态,股吧在我的控制器的服务:

flickrApp.service('shared', function() { 

    var authentication = false; 

    return { 
     getAuth: function() { 
      return authentication; 
     }, 
     setAuth: function (auth) { 
      authentication = auth; 
     } 
    }; 
}); 

这是它不起作用的地方,在我的标签控制器中。 $scope.authData正在$watch函数中正确设置,但是当我尝试在var ref行中使用它时,它说$scope.authData未定义(因此我无法访问uid)。我不知道为什么这不是因为它应该是..

我必须使用$apply与观察器功能以及有什么问题吗?

flickrApp.controller('tagsCtrl', ['$scope', '$rootScope', '$firebase', 'shared', function($scope, $rootScope, $firebase, shared) { 

    $scope.tagsList = []; 
    $scope.shared = shared; 

    $scope.$watch('shared.getAuth()', function(authData) { 
     $scope.authData = authData; 
     console.log($scope.authData); 
    }); 

    var ref = new Firebase ('https://flickr.firebaseio.com/users/' + $scope.authData.uid); 
    var sync = $firebase(ref); 

    $scope.addTag = function(tag) { 

     $scope.tagsList.push(tag); 

     sync.$set({favoriteTags: $scope.tagsList}); 
    } 
}]); 

回答

1

我认为问题在于,在$ watch.set中设置$ scope.authData的数据之前,ref已经完成。尝试将您的代码更改为:

flickrApp.controller('tagsCtrl', ['$scope', '$rootScope', '$firebase', 'shared', function($scope, $rootScope, $firebase, shared) { 

    $scope.tagsList = []; 
    $scope.shared = shared; 
    var ref,sync; 

    $scope.$watch('shared.getAuth()', function(authData) { 
     $scope.authData = authData; 
     console.log($scope.authData); 
     if($scope.authData){ 
      ref = new Firebase ('https://flickr.firebaseio.com/users/' + $scope.authData.uid); 
      sync = $firebase(ref); 
     } 
    }); 



    $scope.addTag = function(tag) { 

     $scope.tagsList.push(tag); 

     sync.$set({favoriteTags: $scope.tagsList}); 
    } 
}]); 
+0

是的,但我认为这并不重要,因为我在设置ref之前运行$ watch。但是,再次,当$ watch首次运行时,认证是错误的,所以我想这可以解释它。无论如何它现在工作。欢呼:) – Chrillewoodz 2015-02-07 09:36:01

+0

如果第一次authData为false,那么你应该在条件下执行赋值给ref。我已经更新了答案。 – 2015-02-07 09:39:29

+0

好点,改变。 – Chrillewoodz 2015-02-07 09:50:39

相关问题