Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$resource.query return split strings (array of char) instead of a string

I am using a angular $resource like the one below.

angular.module('app')
.factory('data', function ($resource) {

    var Con = $resource('/api/data', {}, {
        update : {method : 'PUT'}
    });

    return {     

        getData : function (user_id, callback) {

             return Con.query({user_id : user_id}, function (data) {
                 cb(data); // (breakpoint) HERE data is not good
             }, function (err) {
                 cb(err);
             }).$promise;
         }

   }; 
});

This is what I get when a put a breakpoint on data :

[
    ['w','e','l','c','o','m','e'],
    ['h','e','l','l','o']
] 

howerver, the server sends :

['welcome','hello']

anyone know why the strings get split?

Thank you

like image 451
Hudvoy Avatar asked Jul 21 '14 23:07

Hudvoy


2 Answers

You've run into a fun bug with angular's $resource where it cannot handle a raw array of strings; as a workaround, you can do one of three things:

  • use the $http service instead
  • send an object-wrapped response via the server eg: { "stuff" : [ "your", "strings" ] }
  • force the response data into the above format client-side; $resource eg: methodName: {method:'GET', url: "/some/location/returning/array", transformResponse: function (data) {return {list: angular.fromJson(data)} }} and then access it as data.list

See my answer at https://stackoverflow.com/a/22491240/626810

like image 56
Blaskovicz Avatar answered Oct 15 '22 12:10

Blaskovicz


This works for RAW response. This is a slightly different version from the answer above but this is generic and is not only dependent on JSON response. This will basically mutate RAW response to String format. You will need to access $resource promise result as result.responseData

getAPIService() {
    return this.$resource(this.apiUrl, {}, {
        save: {
            method: 'POST',
            headers: {
                'Accept': 'text/plain, text/xml',
                'Content-Type': 'text/xml'
            },
            transformResponse: function (data) { return { responseData: data.toString() } }
        }
    });
}
like image 44
Sumeet Avatar answered Oct 15 '22 13:10

Sumeet