从不同的脚本AngularJs调用Post

时间:2015-03-26 09:23:17

标签: javascript angularjs

我需要使用帖子来访问服务器端的布尔方法。 它在控制器中工作得很好。

$http.post(ROOT + '/step/ReadOnly/' + $scope.problemId)
        .success(function (result) {
            $scope.problemCompleted = result;

        })
    .error(function (data, status, headers, config) {
        console.log("problemCompleted not sent")
        return false;
    });

问题是我将在很多不同的控制器中使用这种方法。所以我想做的就是把帖子放到服务中,然后就这样从那里调用它。

服务

//readOnly
this.readOnly = function (Id) {
    $http.post(ROOT + '/step/ReadOnly/' + Id)
        .success(function (result) {
            var problemCompleted = result;
            return problemCompleted;
        })
    .error(function (data, status, headers, config) {
        console.log("problemCompleted not sent")
        return false;
    });
};

然后在任何这样的控制器中调用它。

$scope.problemCompleted = stepService.readOnly($scope.problemId);

它仍然调用服务器端控制器,但页面似乎在获得响应之前完成加载。服务器端控制器获得正确的problemId。看起来页面在从帖子中获得结果之前加载,我的$scope.problemCompleted未定义。 它没有点击.success.error它似乎只是跳过它所以我没有得到任何result

1 个答案:

答案 0 :(得分:1)

你不能return from asynchronous code。在您的情况下您可以做和应该做的是返回Promise对象,并在控制器链中返回其可用的API:

this.readOnly = function (Id) {
    return $http.post(ROOT + '/step/ReadOnly/' + Id).success(function (result) {
        return problemCompleted;
    })
    .error(function (data, status, headers, config) {
        console.log("problemCompleted not sent");
        return false;
    });
};

在控制器中:

stepService.readOnly($scope.problemId).then(function(data) {
    $scope.problemCompleted = data;    
});