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
在所有页获取货币的,全部改为:

赞 (0)
