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

Hud*_*voy 27 javascript angularjs

我正在使用像下面那样的角度$资源.

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;
         }

   }; 
});
Run Code Online (Sandbox Code Playgroud)

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

[
    ['w','e','l','c','o','m','e'],
    ['h','e','l','l','o']
] 
Run Code Online (Sandbox Code Playgroud)

然后,服务器发送:

['welcome','hello']
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Bla*_*icz 46

你使用angular的$ resource遇到了一个有趣的bug,它无法处理原始的字符串数组; 作为一种解决方法,您可以执行以下三种操作之一:

  • 请改用$ http服务
  • 通过服务器发送一个对象包装的响应,例如: { "stuff" : [ "your", "strings" ] }
  • 强制将响应数据强制转换为客户端的上述格式; $ resource例如: methodName: {method:'GET', url: "/some/location/returning/array", transformResponse: function (data) {return {list: angular.fromJson(data)} }}然后将其作为data.list

请参阅/sf/answers/1574386831/上的答案

  • 如果服务器返回JSON字符串,则此问题和答案也适用 (6认同)

小智 6

这适用于 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() } }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)