javascript $resource.query 返回拆分字符串(字符数组)而不是字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24876593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:29:44  来源:igfitidea点击:

$resource.query return split strings (array of char) instead of a string

javascriptangularjs

提问by Hudvoy

I am using a angular $resource like the one below.

我正在使用如下所示的有角度的 $resource。

angular.module('app')
.factory('data', function ($resource) {

    var Con = $resource('/api/data', {}, {
        update : {method : 'PUT'}
    });

    return {     

        getData : function (user_id, callback) {

             return Con.query({user_id : user_id}, function (data) {
                 cb(data); // (breakpoint) HERE data is not good
             }, function (err) {
                 cb(err);
             }).$promise;
         }

   }; 
});

This is what I get when a put a breakpoint on data :

这是我在数据上放置断点时得到的结果:

[
    ['w','e','l','c','o','m','e'],
    ['h','e','l','l','o']
] 

howerver, the server sends :

但是,服务器发送:

['welcome','hello']

anyone know why the strings get split?

有谁知道为什么字符串会分裂?

Thank you

谢谢

回答by Blaskovicz

You've run into a fun bug with angular's $resource where it cannot handle a raw array of strings; as a workaround, you can do one of three things:

您在 angular 的 $resource 中遇到了一个有趣的错误,它无法处理原始字符串数组;作为解决方法,您可以执行以下三件事之一:

  • use the $http service instead
  • send an object-wrapped response via the server eg: { "stuff" : [ "your", "strings" ] }
  • force the response data into the above format client-side; $resource eg: methodName: {method:'GET', url: "/some/location/returning/array", transformResponse: function (data) {return {list: angular.fromJson(data)} }}and then access it as data.list
  • 改用 $http 服务
  • 通过服务器发送一个对象包装的响应,例如: { "stuff" : [ "your", "strings" ] }
  • 将响应数据强制转换为客户端的上述格式;$resource eg: methodName: {method:'GET', url: "/some/location/returning/array", transformResponse: function (data) {return {list: angular.fromJson(data)} }}然后作为data.list

See my answer at https://stackoverflow.com/a/22491240/626810

https://stackoverflow.com/a/22491240/626810查看我的回答

回答by Sumeet

This works for RAW response. This is a slightly different version from the answer above but this is generic and is not only dependent on JSON response. This will basically mutate RAW response to String format. You will need to access $resource promise result as result.responseData

这适用于 RAW 响应。这与上面的答案略有不同,但这是通用的,不仅依赖于 JSON 响应。这基本上会将 RAW 响应转变为 String 格式。您将需要访问 $resource promise 结果作为result.responseData

getAPIService() {
    return this.$resource(this.apiUrl, {}, {
        save: {
            method: 'POST',
            headers: {
                'Accept': 'text/plain, text/xml',
                'Content-Type': 'text/xml'
            },
            transformResponse: function (data) { return { responseData: data.toString() } }
        }
    });
}

回答by amit

Use $http instead of $resource

使用 $http 而不是 $resource

getRiskCount: function (Id,Type) {
            var deferred = $q.defer();
            var resource = $resource(urlResolverFactory.hostUrl() + '/api/getstudentriskcount',
                {}, { query: { method: 'GET', isArray: false } }
             );
             resource.query({ userId: Id,userType: Type }, function (data) {
                 deferred.resolve(data);
              }, function (error) {
                  deferred.reject(error);
              });
             return deferred.promise;
          }

  Result - ['4','5','6','7']

 getRiskCount: function (Id,Type) {
                var apiUrl = urlResolverFactory.hostUrl() + '/api/getstudentriskcount';
                apiUrl += '?userId=' + Id,
                apiUrl += '&userType=' + Type;

                var deferred = $q.defer();
                var promise = $http({
                    method: 'GET',
                    url: apiUrl,
                }).success(function (data) {
                    deferred.resolve(data);
                }).error(function (data, status) {

                    deferred.reject(data);
                });
                return promise;
            }

  Result - [4567]