7

我正在尝试在 AngularJS 范围内记录登录用户,但在页面首次加载时出现错误。

单击“登录”似乎可以工作,但随后注销会出现相同的“$apply 已在进行中”错误。

我期待我只是误解了如何$apply工作,有人可以帮忙吗?

更新

如果我只将if (user)部分包装$apply()如下,它可以无缝工作。

var auth = new FirebaseAuthClient(ref, function(error, user) {
    if (user) {
        $scope.$apply(function(){ $scope.user = user; });
        console.log(user);
    } else if (error) {
        // I can't vouch for this, haven't tested it
        $scope.$apply(function(){ $scope.user = null; });
        console.log(error);
    } else {
        $scope.user = null;
        console.log("logged out");
    }
});

原始代码

应用程序.js:

var app = angular.module('app', ['firebase']);

控制器.js:

app.controller('Login', ['$scope', 'angularFire',
function($scope, angularFire) {
    $scope.loginstatus = 'logged out';

    var ref = new Firebase("https://app.firebaseio.com/");
    var auth = new FirebaseAuthClient(ref, function(error, user) {
        if (user) {
            $scope.$apply(function(){ $scope.loginstatus = 'logged in'; });
        } else if (error) {
            $scope.$apply(function(){ $scope.loginstatus = 'error'; });
            alert("Login error: " + error);
        } else {
            $scope.$apply(function(){ $scope.loginstatus = 'logged out'; });
        }
    });

    $scope.login = function(provider, args) {
        auth.login(provider, args);
    }

    $scope.logout = function() {
        auth.logout();
    }
}]);

索引.html:

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="utf-8">
    <title>App</title>
    <script type="text/javascript" src="https://cdn.firebase.com/v0/firebase.js">
    <script type="text/javascript" src='https://cdn.firebase.com/v0/firebase-auth-client.js'></script></script>
    <script type="text/javascript" src="lib/angular/angular.js"></script>
    <script type="text/javascript" src="lib/angularFire.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
    <script type="text/javascript" src="js/controllers.js"></script>
</head>
<body ng-controller="Login">
    <p>Login status: {{loginstatus}}</p>
    <div class="container">
      <h1>Login</h1>
      <p>
        <button ng-hide="user" ng-click="login('twitter')" class="btn btn-primary btn-large">Login</button>
        <button ng-show="user" ng-click="logout()" class="btn btn-primary btn-large">Logout</button>
      </p>
    </div>
</body>
</html>
4

1 回答 1

1

$apply仅当您在 Angular 的上下文之外(如 setTimeout、setInterval 或非 Angular XHR 回调)时才需要。

由于 FireBaseAuthClient 是一个考虑到 Angular 并注入到控制器中的工具,因此回调很可能已经包含在$scope.$apply. 您可以通过删除来修复您的代码$scope.$apply,因此只需:

var ref = new Firebase("https://app.firebaseio.com/");
var auth = new FirebaseAuthClient(ref, function(error, user) {
    if (user) {
        $scope.loginstatus = 'logged in';
    } else if (error) {
        $scope.loginstatus = 'error';
        alert("Login error: " + error);
    } else {
        $scope.loginstatus = 'logged out';
    }
});
于 2013-05-09T02:53:55.113 回答