2015-12-09 20 views
0

我是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),它显示空数组,但你可以看到,服务器的响应是正确的调试菜单:

你能帮我解决这个问题吗?我读了一些Stackoverflow的主题,并尝试了一些编辑,这里描述,但没有为我工作。

回答

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 
      }); 
     } 
    } 
}) 
+0

'错误:citiesService.addCity(...),那么是不是function' ...地段Stackowerflow人民的描述类似的解决方案,但它不是为我工作 – pes502

+0

你可以试试“citiesService.addCity($ scope.city)。$ promise.then [...]”吗? – schneck

+0

是啊,现在我正在玩它,它似乎正在工作,因为我需要!万分感谢! – pes502

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

相关问题