AngularJS没有等待HTTP请求完成

时间:2014-09-07 16:04:06

标签: javascript angularjs angular-promise

大家好,我在这里有以下代码:

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的代码之前没有完成HTTP请求。正在执行$ watch因此它在undefined上调用.length。我对Angular总计n00b,并希望使用这个TodoMVC来使其工作但是我不知道我能做什么来停止整个过程而不是将其余的代码包装在来自http请求的成功回调中。

提前致谢

3 个答案:

答案 0 :(得分:2)

问题

  • #1您需要通过工厂的get方法退回承诺,并使用$http.then代替http的自定义承诺方法success
  • #2您需要链接它,以便为scope属性赋值。
  • #3当您观看异步分配的属性时,您需要进行空检查,因为在设置控制器时手表将会运行。
  • #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.
        });
    },

在您的控制器中: -

   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);

答案 1 :(得分:0)

$http包含在一个承诺中。您可以从服务中返回承诺:

return $http({method: 'GET', url: '/api/todo.php'})

在控制器中,您可以使用then方法指定请求完成时的行为:

 $scope.newTodo = '';
 $scope.editedTodo = null;

todoStorage.get().then(function(result) {

    $scope.todos = result.data;

    $scope.$watch('todos', function (newValue, oldValue) {
        $scope.remainingCount = $filter('filter')($scope.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($scope.todos);
        }
    }, true);
 });

关于如何链接承诺的一个很好的例子:

http://codepen.io/willh/pen/fCtuw

答案 2 :(得分:0)

使用此代码:

angular.module('todomvc')
    .factory('todoStorage', function ($http) {
        'use strict';

    var STORAGE_ID = 'todos-angularjs';

    return {
        get: function () {
            return $http({method: 'GET', url: '/api/todo.php'})
        },

        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';

    $scope.newTodo = '';
    $scope.editedTodo = null;
     todoStorage.get()
         .then(function(d){
          $scope.todos=d;
     })
         .catch(function(e){
          console.error(e);
      })

    $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);