大家好,我这里有以下代码:
angular.module('todomvc')
.factory('todoStorage', function ($http) {
'use strict';
var STORAGE_ID = 'todos-angularjs';
return {
get: function () {
$http({method: 'GET', url: '/api/todo.php'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
return JSON.stringify(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
},
put: function (todos) {
debugger;
localStorage.setItem(STORAGE_ID, JSON.stringify(todos));
}
};
});
以及
angular.module('todomvc')
.controller('TodoCtrl', function TodoCtrl($scope, $routeParams, $filter, todoStorage, $http) {
'use strict';
var todos = $scope.todos = todoStorage.get();
$scope.newTodo = '';
$scope.editedTodo = null;
$scope.$watch('todos', function (newValue, oldValue) {
$scope.remainingCount = $filter('filter')(todos, { completed: false }).length;
$scope.completedCount = todos.length - $scope.remainingCount;
$scope.allChecked = !$scope.remainingCount;
if (newValue !== oldValue) { // This prevents unneeded calls to the local storage
todoStorage.put(todos);
}
}, true);
我遇到的问题是,在执行 $scope.$watch 处的代码之前,HTTP 请求尚未完成,因此它在未定义的情况下调用 .length 。我对 Angular 完全不熟悉,想要使用这个 TodoMVC 来让它工作,但是我不确定我可以做什么来停止整个过程,而不是将其余代码包装在来自 http 请求的成功回调中。
提前致谢
最佳答案
问题
- #1 你需要从工厂的
get
方法返回 Promise,并使用$http.then
而不是 http 的自定义 Promise 方法success
. - #2 您需要将其链接起来才能为范围属性赋值。
- #3 当您监视异步分配的属性时,您需要进行 null 检查,因为监视将在设置 Controller 时运行。
- #4 我不确定您是否应该对响应进行 JSON.stringify,因为看起来您需要数组数据?
在你的工厂
return {
get: function () {
return $http({method: 'GET', url: '/api/todo.php'}). //Return here
then(function(response) { //
return response.data;
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
},
在你的 Controller 中:-
var todos;
todoStorage.get().then(function(data) {
todos = $scope.todos = data
});
和
$scope.$watch('todos', function (newValue, oldValue) {
if(!newValue) return;
$scope.remainingCount = $filter('filter')(todos, { completed: false }).length;
$scope.completedCount = todos.length - $scope.remainingCount;
$scope.allChecked = !$scope.remainingCount;
if (newValue !== oldValue) { // This prevents unneeded calls to the local storage
todoStorage.put(todos);
}
}, true);
关于javascript - AngularJS 不等待 HTTP 请求完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25712193/