防止范围内的项目写入不同用户的记录

2023-11-29

我在应用程序中有一个用户的场景中成功使用了 AngularFire。

现在我已经启动并运行了身份验证,我注意到分配items to $scope.items切换用户时是灾难性的,主要是由于$scope无法正确更新。

直接从文档中阅读...

var ref = new Firebase('https://<my-firebase>.firebaseio.com/items');
angularFire(ref, $scope, 'items');

我需要这些只是items当前授权用户的。所以目前,我这样做(如果有更好的方法,请随时告诉我!)

var ref = new Firebase('https://<my-firebase>.firebaseio.com/items/userId');
angularFire(ref, $scope, 'items');

我生成userId using auth.provider and auth.id, 顺便提一句。现在我的项目已命名为(比方说)user1

var ref = new Firebase('https://<my-firebase>.firebaseio.com/items/[user1id]');
angularFire(ref, $scope, 'items');

我将项目添加到$scope.items

$scope.create = function(item) {

  $scope.items.push(item)
  /* Pretend the user adds these from the interface.
  [
    { name: 'eenie' },
    { name: 'meenie' },
    { name: 'miney' },
    { name: 'moe' }
  ]
  */

}

问题

现在,如果我只是注销并以其他人的身份登录,那么该用户就会神奇地拥有eenie meenie miney and moe因为$scope.items保存注销和登录之间的数组。

我尝试设置$scope.items = []在注销事件上,但这实际上清空了所有记录。我正在拔头发。这只是我项目中需要做的 0.001%,并且花费了我整个周末的时间。

Update新方法

  $scope.create = function() {
    $scope.selectedDevice = {
      name: 'New Device',
      userId: $scope.user.provider + $scope.user.id
    };
    return $scope.devices.push($scope.selectedDevice);
  };

  $scope.$on('angularFireAuth:login', function(evt, user) {
    var promise, ref;
    ref = new Firebase('https://mysite.firebaseio.com/users/' + (user.provider + user.id) + '/registry/');
    promise = angularFire(ref, $scope, 'devices');
  });

现在它将在用户 ID 下准确地创建项目。但是,一旦您注销并重新登录,这些项目就不会被清除。$scope.devices。因此,他们只是将自己添加到数据中,但在新登录的用户下。

Update

我做了很多尝试和错误。我大概设置了$scope.devices to []并以各种可能的组合移动登录事件。最终起作用的是@hiattp 在接受的答案中的修改。


这是由于切换用户时隐式数据绑定保持不变的结果。如果新用户出现并创建新绑定,它将认为现有数据是它应该吸收的本地更改(这就是为什么您会看到原始用户的项目被添加到新用户),但如果您尝试清除它们首先不释放绑定,然后您隐式告诉 Firebase 从原始用户的项目列表中删除该数据(也不是您想要的)。因此,当您根据需要检测到注销(或登录)事件时,需要释放数据绑定。

中的回调angularFirePromise 提供了一个“解除绑定”方法(参见here and here):

var promise = angularFire(ref, $scope, 'items');
promise.then(function(unbind){
  // Calling unbind() will disassociate $scope.items from Firebase
  // and generally it's useful to add unbind to the $scope for future use.
});

您的代码中有一些特质可能会导致它无法工作,请记住unbind不会为您清除本地集合。但只是为了让你知道它是如何发生的should工作(并证明does工作)这里是a fiddle.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

防止范围内的项目写入不同用户的记录 的相关文章

随机推荐