我正在尝试在AngularJS范围内记录登录用户,但在页面首次加载时收到错误。
单击“登录”似乎可以正常工作,但随后注销会出现相同的“$ apply has in progress”错误。
我期待我误解了$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");
}
});
原始代码:
app.js:
var app = angular.module('app', ['firebase']);
controller.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();
}
}]);
的index.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>
答案 0 :(得分:1)
$apply
(如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';
}
});