[AngularJS] transform in $http services

transform is used to format json or whatever return from the server. 

Usage: 

复制代码
Profile.factories = angular.module("profileFactories", []);

Profile.factories.factory('Skills', ['$http', '$q', 'ProfileTransformer', function($http, $q, ProfileTransformer){
    return{
        getSkills: function(){
            var deferred = $q.defer();
            $http({
                url: './public/js/profile/skills.json',
                cache: true,
                method: "GET",
                transformResponse: ProfileTransformer
            })
                .success(function(data){
                    return deferred.resolve(data);
                });
            return deferred.promise;
        }
    }
}]);
复制代码
复制代码
var apiTransform = angular.module("publicTransformer", []);
apiTransform.factory('ProfileTransformer',
    function () {
        return function(data){
            data = JSON.parse(data);
            if(_.size(data)>0){
                data = _.map(data, function(d){
            //Here we format JSON according to what we want!
return {name: d.name, level: d.level, bold_normal: d.b} }) } return data; } });
复制代码

 

Unit Testing: 

复制代码
/**
 * Created by Answer1215 on 9/5/2014.
 */
describe("transform tresponse", function(){
    var transformer, response;

    beforeEach(function () {
        module('publicTransformer');
        inject(function ($injector) {
            transformer = $injector.get('ProfileTransformer');
        });
    });

    it("should return an empty array when it receives an empty array", function(){
        expect(transformer('[]')).toEqual([]);
    });

    it("should return 2 items with name level and b", function(){
        expect(transformer(response)).toEqual([
            {"name": "Hadoop",  "level": "Learning", "b": "normal"},
            {"name": "D3.js", "level": "Learning", "b": "bold"}
        ])
    })

    beforeEach(function(){
        response = JSON.stringify(
            [
                {"name": "Hadoop",  "level": "Learning", "b": "normal"},
                {"name": "D3.js", "level": "Learning", "b": "bold"}
            ]
        )
    })
})
复制代码

 

posted @   Zhentiw  阅读(295)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示