AngularJS。可以在$ resource工厂添加自定义属性吗?

时间:2014-11-27 15:46:12

标签: angularjs angular-resource angular-services

我有一个基于HTTP的RESTful API 当我连接到例如www.domain.com/chiamate/ELSENWZ时,我得到了这个结果:

{
"TICKET": "155112-I",
"TICKET_2": "ATRE6463",
"ACCOUNT_NAME": "PIPPO",
"CUSTOMER_NUMBER": "AG5",
"PROBLEM_TYPE": "H",
"VENDOR": "ITALWARE-CON",
"DESCR": "HP 6300 PRO SFF",
}

我已经在AngularJS中实现了一种服务,以这种方式使用其余的api:

var services = angular.module('ngdemo.services', ['ngResource']);

services.factory('ChiamataFactory', function ($resource) {
return $resource('/chiamate/:id', {}, {
    show: { method: 'GET',
            isArray: false, // <- not returning an array
            transformResponse: function(data, headers){
                var wrapped = angular.fromJson(data);
        alert(JSON.stringify(wrapped, null, 4));
                angular.forEach(wrapped.items, function(item, idx) {
                    wrapped.items[idx] = new Post(item); //<-- replace each item with an instance of the resource object
                });
                return wrapped;
            } },
    create: { method: 'POST' },
    update: { method: 'PUT', params: {id: '@id'} },
})
});

因为我想在控制器使用服务时

$scope.chiamata = ChiamataFactory.show({id: 'ELSENWZ'});

结果我需要添加一些额外的属性。

问题是服务没有使用transformResponse

1 个答案:

答案 0 :(得分:0)

无法使用transformResponse使用来自异步服务的数据来装饰数据

试试这个伪代码

angular.module('myApp').service('MyService', function($q, $resource) {
  var getResult = function() {
    var fullResult = $q.defer();
    $resource('url').get().$promise.then(function(data) {
     var partialPromises = [];
      for (var i = 0; i < data.elements.length; i++) {
       var ires = $q.defer();
       partialPromisses.push(ires);
       $resource('url2').get().$promise.then(function(data2) {
        //do whatever you want with data
        ires.resolve(data2);
        });
       $q.all(partialPromisses).then(function() {
      fullResult.resolve(data);
    });
    return fullResult.promise; // or just fullResult
    }
  });
  };
  return {
    getResult: getResult
  };
});

或者您可以transformResponce使用$http,如文档

中所述

angular $http documentation