如何扩展AngularJS资源

时间:2015-05-17 20:26:51

标签: angularjs resources

要将json对象属性从String调整为Date以抑制AngularJS警告,日期输入的datefmt错误。 问题是:以下代码可以实现,但有点难看,是否有更美观的实现?

'use strict';

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

ahbHotelService.factory('Hotel',['$resource',function($resource){

    var AHBHotel = $resource('/api/hotel/:id',{},{
        query:{method:'GET',params:{id:''},isArray:true}
    });

    var protoGet = AHBHotel.get;
    AHBHotel.get = function(params){
        var result =  protoGet(params);
        result.$promise.then(function(){
            result.created = new Date(result.created);
        });
        return result;
    };
    return AHBHotel;
}]);

1 个答案:

答案 0 :(得分:0)

'use strict';

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

ahbHotelService.factory('Hotel',['$resource',function($resource){    
    return $resource('/api/hotel/:id',{},{
        query:{method:'GET',params:{id:''},isArray:true},
        get:{
            method:'GET',
            transformResponse:function(data,headers){
                var obj = JSON.parse(data);
                if(obj.created)obj.created = new Date(obj.created);
                return obj;
            }
        }
    });
}]);