我需要使用帖子来访问服务器端 bool 方法。 它在像这样的 Controller 中工作得很好。
$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;
});
问题是我将在很多不同的 Controller 中使用这种方法。所以我想做的就是将帖子放入服务中,然后像这样从那里调用它。
服务
//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;
});
};
然后在任何 Controller 中调用它,如下所示。
$scope.problemCompleted = stepService.readOnly($scope.problemId);
它仍然调用服务器端 Controller ,但页面似乎在获得响应之前已完成加载。服务器端 Controller 获取正确的 problemId
。似乎页面在获得帖子结果之前就已加载,而我的 $scope.problemCompleted
未定义。
它没有命中 .success
或 .error
它似乎只是跳过它,所以我没有得到任何结果
。
最佳答案
你不能return from asynchronous code 。对于您的情况,您可以而且应该做的是返回 Promise对象并在 Controller 链中连接到其可用的 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;
});
};
在 Controller 中:
stepService.readOnly($scope.problemId).then(function(data) {
$scope.problemCompleted = data;
});
关于javascript - 从不同的脚本 AngularJs 调用 Post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29274835/