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

1

9

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'
            }
        }
    }
]);
Avebury answered 29/7, 2015 at 22:31 Comment(2)
So how are you calling the count method on the resource?Thordia
I don't see anything in the defaultHttpResponseTransform that would turn your string into an array. You'll need to show your code where you call the resource method and handle the responseAlessandraalessandria
H
8

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) }
        [...]
Hindman answered 29/7, 2015 at 22:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.