2013-04-10 71 views
1

所以看起来我的要求:

angular.module('todoApp').factory('UsersService', ['$resource', 'paramsService', '$q', function($resource, paramsService, $q){ 
var server = paramsService.serverUrl; 
return { 
    'auth': function(username, password){ 
     var $response = {}; 
     $resource(server + '/api/account/auth', {}, {call: {method: 'POST', headers: {'Content-Type': 'application/json'}}}).call(
      {'username': username, 'password': password}, 
      function(data){ 
       console.log(data); 
       $response = data; 
      } 
     ); 
     console.log($response); 
     return $response; 
    }, 
    } 
}]); 

在数据成功功能我HAVA响应,但变量$回应是空的。我知道,但为什么会发生,但无法找到方法等待响应返回它。我如何获得$资源的回应?

+0

查看docs.angularjs网站上的教程示例。范围项目接受承诺 – charlietfl 2013-04-10 14:13:36

回答

0

由于charliefl评论说您需要使用$ resource请求返回的promise对象来等待函数完成($ resource is asynchronous)。

我的用于处理POST请求的PHP代码返回了写入文件的字节数。我使用下面的代码从响应中解析了它。由于'资源'对象不是真正的数组(像'参数'),我必须遍历可能的索引,直到返回'undefined'。

所以底线是什么在你的响应正文将作为资源对象的字节数组返回给你。

$resource(...POST REQUEST...) 
     .$promise.then(function (resource) { 
      var bytesSaved = ''; 
      var i = 0; 
      while (resource[i] !== undefined) { 
       bytesSaved += resource[i]; 
       i++; 
      } 
      $scope.lessonMsg = 'File saved, ' + bytesSaved + ' bytes' 
     } 
     function(error) { 
      $scope.msg = 'An error occurred trying to save the file. ' + error; 
     } 
    ); 

这里是PHP代码生成POST响应:

case "POST": 
    $params = explode("file/", $_SERVER['REQUEST_URI']); 
    $filename = '../common/resources/fileContents' . $params[1] . '.json'; 
    $data = file_get_contents("php://input"); 
    $data = json_decode(file_get_contents("php://input"),false); 
    $fileJson = file_put_contents($filename, json_encode($data)); 
    echo $fileJson; 
break; 

的file_put_contents()调用返回写入或假,如果有错误的字节数。