Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

ngResource is not suitable for single primitive value(such as string or number) response #12787

@kuitos

Description

@kuitos

the web api(restful most of time) may return a single primitive value as response,such as a string or a number, like this

GET /users/count  ----> 10
GET /users/1/name ------> "Jack"

single primitive value(string or number or true&false and so on) is conform to the specifications of JSON,but now ngResource just support Array or Object response,and I know the reason when I saw the ngResource source code:

........
if (action.isArray) {
  value.length = 0;
  forEach(data, function(item) {
    if (typeof item === "object") {
      value.push(new Resource(item));
    } else {
      // Valid JSON values may be string literals, and these should not be converted
      // into objects. These items will not have access to the Resource prototype
      // methods, but unfortunately there
      value.push(item);
    }
  });
} else {
  shallowClearAndCopy(data, value);
  value.$promise = promise;
}
..........
/**
 * Create a shallow copy of an object and clear other fields from the destination
 */
function shallowClearAndCopy(src, dst) {
  dst = dst || {};

  angular.forEach(dst, function(value, key) {
    delete dst[key];
  });

  for (var key in src) {
    if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
      dst[key] = src[key];
    }
  }

  return dst;
}

Obviously it can not resolve single string or number response.
What should I do when the response is single string with ngResource?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions