angularjs $resource将查询资源列表转换为对象数组

angularjs $resource converting query Resource list to array of objects

本文关键字:转换 对象 数组 列表 资源 resource 查询 angularjs      更新时间:2023-09-26

我正在尝试从$resource查询的返回中创建对象数组,如以下SO问题所示:链接。但是,我不断得到相同的资源和其他元素列表。 我有一个 plunk:这里(您必须打开开发人员控制台才能看到输出。

var app = angular.module('plunker', ['ngResource']);

app.factory('NameResource', function($resource) {
  var url = 'data.json';
  var res = $resource(url, null, {
    query: {
      method: 'GET',
      isArray: true,
      transformResponse: function(data, headersGetter) {
        var items = angular.fromJson(data);
        var models = [];
        angular.forEach(items, function(item) {
          models.push(item);
        });
        console.log("models: ", models);
        return models;
      }
    }
  });
  return res;
});
app.controller('MainCtrl', function($scope, NameResource) {
  $scope.names = NameResource.query();
  console.log('Inside controller: ', $scope.names);
  setTimeout(function(){console.log('after some time names is:', $scope.names)}, 3000);
});

我做错了什么? 还是我误解了什么。 还有两者有什么区别?对我来说,它似乎非常相似。 什么时候会导致问题?

Resource.query返回一个具有两个属性的数组(因为您创建的 isArray 标志),$promise这是一个承诺,当解析时,它将"复制"所有响应值到从返回的数组Resource.query神奇地更新视图和$resolved这是一个标志,告诉$promise是否已解析, 为了回答您的问题,实际上发生了一些额外的转换,从转换返回的数据实际上将经过另一个转换(无法禁用),这是每个对象转换为Resource实例的地方。

所以这就是你期望发生的事情:

promise
    .then(function (rawData) {
        // this is where your transformation is happening
        // e.g. transformResponse is called with rawData
        // you return your transformed data
    })
    .then(function (transformedData) {
        // raw data has gone through 1 transformation
        // you have to decide what to do with the data, like copying it to
        // some variable for example $scope.names
    })

Resource正在执行以下操作:

promise
    .then(function (rawData) {
        // this is where your transformation is happening
    })
    .then(function (transformedData) {
        // Resource is adding this handler and doing the
        // 'copy' to array operation here for you,
        // but it will actually create a Resource instance 
        // in the process with each item of your array!
    })
    .then(function (transformedDataV2) {
       // raw data has gone through 2 transformations here!             
    })

额外的转换是魔术发生的地方,也是创建Resource实例的地方,如果我们看一下源代码,这些是处理这种转换的行,我将在这里复制它们:

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

data是第一次转换返回的数据,如上所示,它将通过typeof item === 'Object'检查,因此value Resource.query返回的数组将更新为新的Resource项(而不是项)。你担心这个奇怪的Resource对象,让我们分析一下Resource构造函数:

function Resource(value) {
  shallowClearAndCopy(value || {}, this);
}

它只是将对象的每个属性value复制到thisthis是新的 Resource 实例),所以现在我们处理的是Resource对象而不是纯数组对象

它会导致问题吗?

我相信它会的,如果你定义的转换函数稍微复杂一点,比如让每个对象实际上是其他东西的实例,其__proto__有一些方法,例如Person对象而不是普通对象,那么Person.prototype中定义的方法对整个操作的结果不可见,因为每个对象都不是Person实例,而是Resource实例!(在此 plunkr 中看到此错误,请务必阅读注释并查看由于未定义方法而在控制台中引发的错误)