0

I'm working with php Tonic and AngularJS. So I have angular that call a rest resource. The code of the rest is like this:

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

On backend, code return a Response object with an array in the body. From angular I use $resource service to call backend:

return {

    getBackData : function(){

        var call = $resource('/table_animation_back/comunication');

        call.get(function(data){
            console.log(data);
        });

    }

}

The result of console.log is this:

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

I tried to use:

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

but Response in php is an object and not an array, so in this way I got a javascript error. I can't access to the array. Where wrong?

mrdaino
  • 331
  • 1
  • 4
  • 10

2 Answers2

1

You need to serialize your array to JSON before sending to client:

public function getData(){
    $response = new Response();
    $response->code = Response::OK;
    // Encode the response:
    $response->body = json_encode(array("one","two"));
    return $response;
}
Constantine Poltyrev
  • 1,015
  • 10
  • 12
  • thank you it work. Now i have to use call.query() and not call.get(). But isn't there a way to send array without use json? – mrdaino Nov 01 '15 at 15:09
0

I think that you forgot encode data before return it to client. In the server-side, it should be:

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

In client, I think that we should use $q.defer in this case. For example:

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;
        }
    };
});
Nguyen Sy Thanh Son
  • 5,300
  • 1
  • 23
  • 33