Search code examples
javascriptarraysangularjsangularjs-serviceangularjs-resource

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'
            }
        }
    }
]);

Solution

  • 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) }
            [...]