【问题标题】:Angular resource with response type text/plain always makes an array of strings响应类型为 text/plain 的 Angular 资源总是创建一个字符串数组
【发布时间】:2015-10-21 03:11:01
【问题描述】:

我将从 rest 服务接收记录的资源设为纯文本。 Angular 从答案中生成每个字符的数组。例如,如果 rest 回答 20,则 angular 将生成数组 [2,0]。我可以在不转换响应或使用$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'
            }
        }
    }
]);

【问题讨论】:

  • 那么你是怎么调用资源的count方法的呢?
  • 我在defaultHttpResponseTransform 中看不到任何可以将您的字符串转换为数组的内容。您需要在调用资源方法并处理响应的位置显示代码

标签: javascript arrays angularjs angularjs-service angularjs-resource


【解决方案1】:

Angular 难以检索带有$resource 的字符串列表。您包括的一些选项(由于您的问题的限制,建议两个可能是您想要的)...

  1. 选择使用$http 服务

  2. 以包装对象的形式返回您的响应,例如 { 'collection': [20, 40, 60] }

  3. 通过定义的属性转换响应和访问,例如data.collection。转换您的响应的示例可能包括...


return $resource('/rest/records/:id', {}, {
    count: { 
        method:'GET',
        transformResponse: function (data) {
            return { collection: angular.fromJson(data) }
        [...]

【讨论】:

    猜你喜欢
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 2013-02-28
    • 2023-01-20
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多