javascript - AngularJS 不等待 HTTP 请求完成

标签 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.$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/

相关文章:

javascript - 在 JavaScript 中将 HTTP 响应主体与 header 分开

javascript - 混合 $q 和 ES6 promise 时测试 Angular

javascript - 使用 ngResource、socket.io 和 $q 维护资源集合

javascript - Angular promise 行为

javascript - Mongoose 集合中的随机文档

javascript - 有没有办法找到所有在样式中使用视口(viewport)单位的 HTML 元素?

javascript - 如何使用 angularjs 验证动态创建的表单?

javascript - transformRequest 仅针对 angularJS 中的特定请求

javascript - javascript 函数表达式是否类似于或基于 s 表达式?

javascript - XML 到 HTML 表中以用于传单 map 标记弹出窗口