0

我有一个服务 angularjs 的问题,不要发出多个 http 请求。

服务 :

.factory('checkpoints', function($http, user_auth) {
            var promise = $http({
                method: "POST",
                url: remote_ws + 'index/',
                data: user_auth.get,
                cache:false
            }).
                    success(function(data, status, headers, config) {
                        if (data.result == "OK") {
                            window.localStorage.setItem("last_id", data.update[0].last_id);
                            window.localStorage.setItem("last_count", data.update[0].last_count);
                        }
                        return data;
                    }).
                    error(function(data, status, headers, config) {
                        data.result = "ERROR";
                        data.status = status;
                        return data;
                    });
            return promise;
        })

在控制器中:

var UpdateCheckpoints = function() {
        checkpoints.then(function(promise) {
            if (promise.data.result == "OK") {
                $scope.map.checkpoints = promise.data.markers;
                _.each($scope.map.checkpoints, function(marker) {
                    marker.distance = $scope.c_distance(marker);
                    marker.onClicked = function() {
                        onMarkerClicked(marker.id);
                    };
                });
            } else {
                $location.search({error: true, error_text: session_error}).path("/login");
                if (!$scope.$$phase) {
                    $scope.$apply();
                }
            }
        })

当我调用:UpdateCheckpoints () 时,结果为空。

只完成第一个请求。

$http服务声明有问题吗?

4

1 回答 1

1

文档中:

Angular 服务是单例对象或函数......

服务工厂函数的目的是生成向应用程序的其余部分表示服务的单个对象或函数。

尝试将您的工厂更改为以下内容:

app.factory('checkpointService', function($http, user_auth) {

  return {
    getCheckpoints: function() {

      return $http({
          method: "POST",
          url: remote_ws + 'index/',
          data: user_auth.get,
          cache: false
        })
        .success(function(data, status, headers, config) {
          if (data.result == "OK") {
            window.localStorage.setItem("last_id", data.update[0].last_id);
            window.localStorage.setItem("last_count", data.update[0].last_count);
          }
          return data;
        })
        .error(function(data, status, headers, config) {
          data.result = "ERROR";
          data.status = status;
          return data;
        });
    }
  };
});

并调用它:

checkpointService.getCheckpoints().then(function(promise) { ...

现在checkpointService将是一个单例对象,但每次您getCheckpoints通过服务调用新调用时$http都应该进行。

于 2014-02-20T20:53:38.463 回答