【发布时间】:2014-07-05 11:41:14
【问题描述】:
这是我想要做的:
我在一个项目中使用 AngularJS 和 firebase: 1. 发生匿名登录,然后 2. 使用我可以检索的 ID 为该登录创建了 firebase 数据存储中的记录 3. 数据结构中添加了一些其他信息(用户的名字和其他一些信息)。
我想使用 ng-repeat 显示许多 HTMl 元素,这些元素与与用户及其会话相关联的数字相对应。他们有机会增加或减少此金额。例如,如果他们将这个数字增加到 10,我想使用 ng-repeat 来显示 10 个 HTML 元素。如果他们将其减少到 9,则显示 9,等等。
我遇到的问题是在 Firebase 中查询与其特定匿名登录相关联的记录。 firebase 简单登录返回一个承诺,我使用 firebase getCurrentUserID() 方法等待并能够在从服务器返回会话后检索匿名用户 ID。
这是我目前的代码
(这一切都在控制器中以供查看)
// wire a new Firebase connection
var ref = new Firebase('https://myfirebaseloginexample.firebaseio.com');
// connect the user object to the firebase
$scope.userRef = $firebase(ref);
// wire anonymous login
$scope.loginObj = $firebaseSimpleLogin(ref);
// wait for the anonymous login data to load and persist
$scope.loginObj.$getCurrentUser().then(function() {
console.log($scope.loginObj.user.id);
});
我已经能够使用当前匿名会话来查询 Firebase 中的关联数据并使用以下代码(也在控制器中)递增它
// increment the number of boxes
$scope.incrementboxCount = function() {
// assign the session id to a variable
var uniqueSessionChildID = $scope.loginObj.user.id;
// pass the assigned id variable into the firebase connection, where we will find the reference with the current child (the sesison ID)
var sessionLoc = $scope.userRef.$child(uniqueSessionChildID);
// get the current number of boxes at the location in firebase ref specified by the session ID
var getBoxes = sessionLoc.numberBoxes;
// find the firebase reference that we want by ID, update it and increment the amount of boxes
$scope.userRef.$child(uniqueSessionChildID).$update({
numberBoxes: getBoxes + 1
});
};
相关的html:
<div ng-model="(not sure of proper model)">
<div ng-repeat="box in boxes">
<h1>How many boxes?</h1>
<h4>{{not sure of proper express here}}</h4>
</div>
</div>
我尝试访问 loginObj 数据(特别是唯一的匿名 ID)以便查询 Firebase 引用,但它在堆栈跟踪中出现空响应。我猜这是因为它在实际解决之前就被调用了,但我不知道如何解决这个问题(我确信这是一个简单的修复,我只是没有得到或不知道) .
非常感谢!
【问题讨论】:
-
如果我理解得很好,您正在尝试获取当前用户,但控制器在响应之前加载,这在您不使用解析时是正常的,因此您的当前用户为 null 并且您可以不要做任何事情,因为其余的逻辑取决于它,对吧?
-
正确!我对 js 的角度和更广泛的使用有点陌生(我知道这很尴尬等等),所以我确信有更好的方法来做到这一点,我只是不知道。谢谢!!
-
虽然我应该添加我可以增加和减少firebase ref中的数字,但我的问题是再次访问它
标签: angularjs angularjs-scope angularjs-ng-repeat firebase angularfire