Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular resource with response type text/plain always makes an array of strings

I made resource that receive records count from rest service as text plain. Angular makes an array of each chars from answer. For example if rest answers 20, angular will make array [2,0]. Can I fix it without transforming response or using $http?

var resource = angular.module('resource');
resource.factory('RecordResource', ['$resource',
    function($resource) {
        return $resource('/rest/records/:id', {}, {
            count: {
                method:'GET',
                url: "/rest/records/count",
                isArray: false,
                responseType: 'text'
            }
        }
    }
]);
like image 978
nuclear kote Avatar asked Jul 29 '15 22:07

nuclear kote


1 Answers

Angular has difficulty retrieving a list of strings with $resource. Some options you have include (suggestion two being what you likely want due to constraints in your question)...

  1. Opting to leverage the $http service instead

  2. Return your response in a wrapped object such as { 'collection': [20, 40, 60] }

  3. Transform the response and access through a defined property e.g. data.collection. An example for transforming your response could include...


return $resource('/rest/records/:id', {}, {
    count: { 
        method:'GET',
        transformResponse: function (data) {
            return { collection: angular.fromJson(data) }
        [...]
like image 131
scniro Avatar answered Oct 24 '22 05:10

scniro