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

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


我的问题是HTTP请求在$ scope。$ watch的代码执行之前没有完成,因此它在未定义的位置调用.length。我对Angular总共n00b,想使用此TodoMVC使其正常工作,但是我不确定我该怎么做才能停止整个过程,而不是将其余代码包装在来自HTTP请求的成功回调中。

提前致谢

最佳答案

问题


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

07-28 02:50
查看更多