AngularJS$资源可以';t将数组反序列化为对象


AngularJS $resource can't deserialized array into an object

我正在使用php Tonic和AngularJS。所以我有一个称为休息资源的角。其余部分的代码如下:

/**
 * @method GET
 */
public function getData(){
    $response = new Response();
    $response->code = Response::OK;
    $response->body = array("one","two");
    return $response;
}

在后端,代码返回一个主体中带有数组的Response对象。从angular我使用$resource服务调用后端:

return {
    getBackData : function(){
        var call = $resource('/table_animation_back/comunication');
        call.get(function(data){
            console.log(data);
        });
    }
}

console.log的结果是:

Resource {0: "A", 1: "r", 2: "r", 3: "a", 4: "y", $promise: d, $resolved: true}0: "A"1: "r"2: "r"3: "a"4: "y"$promise: d$resolved: true__proto__: Resource

我尝试使用:

call.query(function(){...})

但是php中的Response是一个对象,而不是数组,所以通过这种方式我得到了一个javascript错误。我无法访问数组。哪里错了?

在发送到客户端之前,您需要将数组序列化为JSON:

public function getData(){
    $response = new Response();
    $response->code = Response::OK;
    // Encode the response:
    $response->body = json_encode(array("one","two"));
    return $response;
}

我认为您在将数据返回到客户端之前忘记了对数据进行编码。在服务器端,它应该是:

$response->body = json_encode(array("one","two"));
return $response;

在客户端中,我认为在这种情况下我们应该使用$q.defer。例如:

angular.module('YourApp').factory('Comunication', function($http, $q) {
    return {
        get: function(token){
            var deferred = $q.defer();
            var url = '/table_animation_back/comunication';
            $http({
                method: 'GET',
                url: url
            }).success(function(data) {
                deferred.resolve(data);
            }).error(deferred.reject);
            return deferred.promise;
        }
    };
});