3

我想$scope.me被动地代表当前登录的用户,以便当用户注销并以另一个用户身份重新登录时,此变量会更新。现在,当用户注销并以另一个用户身份重新登录时,旧值$state.me仍然存在。重新加载页面后,此值将被更正。我该如何解决?

这是我在控制器中的工作,糟糕的解决方案:

$scope.$on('$ionicView.enter', function(e) {
    if($rootScope.currentUser)
        $scope.me = $rootScope.currentUser;

});

这有效,但每次用户转换到此状态时都会重置变量......一个丑陋的非流星解决方案。

这是我目前的尝试:

$scope.me = ($scope.$meteorCollection(function(){
    return Meteor.users.find({_id: Meteor.userId()});
}))[0];

这应该可以工作,因为 Meteor.userId() 是反应性的,并且应该强制它的父函数在它发生变化时重新运行,从而$scope.me实时更正......但它没有。

而是$scope.me更新为旧用户的经过清理的配置文件......除了他们的_idprofile可见之外什么都没有。这告诉我$scope.$meteorCollection正在重新运行,但旧值为Meteor.userId().

我错过了什么?谢谢!

* 编辑 * 这是一个转折点

$scope.me = ($scope.$meteorCollection(function(){
    console.log("$scope.me reset to "+Meteor.userId());
    return Meteor.users.find({_id: Meteor.userId()});
}))[0];

当用户切换时,将新用户的 ID打印到控制台,但即使使用正确的值重新运行查询,仍会返回旧用户。

4

2 回答 2

3

您是否尝试过使用$rootScope.currentUser而不是尝试烘焙自己的解决方案?Angular-Meteor会自动为你创建这个 $rootScope 对象,文档说它是反应式的。

另一种可能的解决方案是使用$meteor.autorun便捷方法,但不是基于 $scope 变量的更改自动运行,您可以使用if(Meteor.userId())or之类的东西if(Meteor.user())

事实上,如果您查看源代码,这就是 Angular-Meteor 在幕后所做的事情。

文档

// Updated to check for deep equality on the getReactively() call
$meteor.autorun($scope, function() {
     $scope.userForScore = $scope.$meteorObject(Userinfo, 
        {user_id: $scope.getReactively('currentUser', true)._id}
     );// Ultimately searches up scope chain for $rootScope.currentUser._id
});
于 2015-09-03T20:52:37.367 回答
0

我找到了一个解决方案:

$meteor.autorun($scope, function(){
    var user = (Meteor.users.find({_id: Meteor.userId()}).fetch())[0];
    if( user != null ){
        $scope.me = user;
    }
});

$meteor.autorun自动重新运行函数中包含的反应性依赖项。在这种情况下,Meteor.userId()。因此,每当流星改变它时,函数体就会重新运行,$scope.me如果用户登录,则设置为当前用户。

感谢 JacobWuzHere 的提示!

于 2015-09-04T20:38:59.670 回答