zoukankan      html  css  js  c++  java
  • Angularjs实现一个Factory

    昨晚对项目程序进行重构,发现一些数据冗余非常严重,一些货币,单位等静态数据N个页面均有从数据库获取。

    因此,Insus.NET想到了,把它们写成一个通用的方法。在页面中,直接去执行此通用的方法即可。

    代码示例大约如下:

    公共函数:

    function httpRequestEvent(type, url, args) {
            var d = $q.defer(); //声明延后执行,表示要去监控后面的执行。
            $http({
                method: type,
                url: url,
                dataType: 'json',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                data: JSON.stringify(args)
            })
                .then(
                    function successCallback(response) {
                        d.resolve(response.data); //执行成功,即http请求数据成功,可以返回数据了。
                    },
                    function errorCallback(response) {
                        d.reject(response); //执行失败,即服务器返回错误。
                    });
            return d.promise; //返回承诺,这里并不是最终数据,而是访问最终数据的API。
        }
    Source Code

    独立引用公共函数:

     factory.currs = function () {
            var deferred = $q.defer();
    
            var args = {};
            httpRequestEvent('POST', '/Code/Currencies', args).then(function (data) {
                deferred.resolve(data);
            });
    
            return deferred.promise;
        };
    Source Code

    在所有页获取货币的,全部改为:

  • 相关阅读:
    简单poi创建execl
    Orcale 存储过程实践总结
    PLSQL 创建自定义函数注意事项
    字符串算法模板整理
    多项式FFT/NTT模板(含乘法/逆元/log/exp/求导/积分/快速幂)
    UVALive
    Gym
    Gym
    Kattis
    Kattis
  • 原文地址:https://www.cnblogs.com/insus/p/12572250.html
Copyright © 2011-2022 走看看