Javascript 从不同脚本调用帖子AngularJs
我需要使用post来访问服务器端的布尔方法。 它在这样的控制器中工作良好Javascript 从不同脚本调用帖子AngularJs,javascript,angularjs,Javascript,Angularjs,我需要使用post来访问服务器端的布尔方法。 它在这样的控制器中工作良好 $http.post(ROOT + '/step/ReadOnly/' + $scope.problemId) .success(function (result) { $scope.problemCompleted = result; }) .error(function (data, status, headers, config) {
$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;
});
$scope.problemCompleted = stepService.readOnly($scope.problemId);
问题是,我将在许多不同的控制器中使用这种方法。所以我想做的是把帖子放到一个服务中,然后像这样从那里调用它
$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;
});
$scope.problemCompleted = stepService.readOnly($scope.problemId);
服务
//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;
});
};
然后像这样调用任何控制器
$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;
});
$scope.problemCompleted = stepService.readOnly($scope.problemId);
它仍然调用服务器端控制器,但页面似乎在收到响应之前完成加载。服务器端控制器获取正确的问题ID
。页面似乎在从帖子中获得结果之前就加载了,我的$scope.problemCompleted
未定义。
它没有击中.success
或.error
它似乎只是跳过了它,所以我没有得到任何结果
你不能。在您的情况下,您可以并且应该做的是将对象和控制器链中的对象返回到其可启用的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;
});
谢谢您的回答。@EricColgan您不应该创建多余的延迟对象,因为
$http
已经返回了Promise对象。啊,太好了,我现在明白了。我现在用你的方式,它干净多了。干杯