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?

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

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?
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;
        }
    };
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.