我有一个 Controller 和服务。
该服务执行 http.get
并在成功时返回 true,如果错误则返回 false。
然而,在 Controller 中,它正确接收true
或false,但绑定(bind)的html始终显示为true?
Controller :
app.controller('MyController', function($scope, MyService) {
MyService.getData(function(isLoggedIn, userData) {
var loggedIn = isLoggedIn;
$scope.isLoggedIn = loggedIn;
$scope.myUser = userData;
//$scope.$evalAsync();
//$scope.$apply();
});
});
app.factory('MyService', function($http, $q) {
return {
getData: function(isLoggedIn, userModel) {
$http.get('../assets/data/data.json')
.success(function(data) {
userModel(data);
isLoggedIn(true);
})
.error(function(data, status, headers, config) {
// If 400 or 404 are returned, the user is not signed in.
if (status == 400 || status == 401 || status == 404) {
isLoggedIn(false);
}
});
}
}
});
HTML:
{{isLoggedIn}}
在上面,{{isLoggedIn}}
始终为 true。即使我将 http 调用修改为:
$http.get('../blah/blah/blah.json')
努力强制发生错误/失败。
我已经尝试过 $scope.$apply() 并且我不断收到进程中摘要循环的错误。帮助!!!
最佳答案
我认为您对回调的工作方式有点困惑。服务中的 isLoggedIn
参数是您传入的回调函数。更正的代码:
app.controller('MyController', function($scope, MyService) {
/*
The function(response) { is your callback function being passed to the service
*/
MyService.getData(function(response) {
var loggedIn = response.isLoggedIn;
$scope.isLoggedIn = loggedIn;
$scope.myUser = response.userModel;
});
});
app.factory('MyService', function($http, $q) {
return {
getData: function(callback) {
$http.get('../assets/data/data.json')
.success(function(data) {
//Execute your callback function and pass what data you need
callback({userModel: data, isLoggedIn: true});
})
.error(function(data, status, headers, config) {
// If 400 or 404 are returned, the user is not signed in.
if (status == 400 || status == 401 || status == 404) {
callback({isLoggedIn: false});
}
});
}
}
});
您应该使用 Promise...这是一个更加重构的版本:
app.controller('MyController', function($scope, MyService) {
MyService.getData().then(function(response) {
var loggedIn = response.isLoggedIn;
$scope.isLoggedIn = loggedIn;
$scope.myUser = response.userModel;
});
});
app.factory('MyService', function($http, $q) {
return {
getData: function() {
return $http.get('../assets/data/data.json')
.then(function(response) {
return {
userModel: response.data,
isLoggedIn: true
};
}, function(data, status, headers, config) {
// If 400 or 404 are returned, the user is not signed in.
if (status == 400 || status == 401 || status == 404) {
return {isLoggedIn: false};
}
});
}
}
});
关于javascript - 服务调用后 Angular 范围未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35180342/