我是AngularJS的新手,我遇到了这个问题。我已经使用方法citiesService
定义了服务addCity
:
.service('citiesService', ['$resource', function($resource){
this.addCity = function(city) {
var cityItem = $resource("server/?module=cities&action=add", {}, {save: {method: "POST", isArray:true}});
return cityItem.save({
city: city
});
};
}])
它工作正常,新城市通过PHP脚本成功添加到数据库中,但我不知道如何返回服务器响应。服务器返回响应如:
$output = [];
$output[] = ["success" => "added to database"];
echo json_encode($output);
然后我有了这个控制器:
.controller('citiesAddCtrl', function($scope, $modalInstance, citiesService) {
// save addCity form (modal)
$scope.saveForm = function() {
if($scope.city.name) {
$scope.a = citiesService.addCity($scope.city);
}
}
})
但我真的不知道如何显示服务器JSON响应。当我尝试像console.log($scope.a)
这样的东西时,它显示了空数组,但正如您所看到的,服务器响应位于正确的调试菜单中:
答案 0 :(得分:1)
由于save
会返回一个承诺,您可以按以下方式访问该响应(未经测试):
.controller('citiesAddCtrl', function($scope, $modalInstance, citiesService) {
// save addCity form (modal)
$scope.saveForm = function() {
if($scope.city.name) {
citiesService.addCity($scope.city).$promise.then(function(response) {
$scope.a = response
});
}
}
})
答案 1 :(得分:0)
为什么不使用具有明确承诺结构的$ http?
$http({
method: 'POST',
url: "server/?module=cities&action=add",
data: $scope.city
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
请参阅$http
上的文档