最近看到说在controller中进行数据处理不是很合适,所以就去学习了Controller与Service进行分层设计与编码,参考了http://www.jianshu.com/p/1e1a...,但是我在使用过程遇到的一个问题就是在Service层处理通讯回调,将业务回调传递给Controller层这种方式调用$http服务的时候,如何传递请求参数呢?代码如下:
angular.module('demo')
.service('myService',['$http','$q',function($http,$q){
return {
getData:function(){
var deferred = $q.defer();
var promise = $http.get("xxx");
promise.then(
// 通讯成功的处理
function(answer){
//在这里可以对返回的数据集做一定的处理,再交由controller进行处理
answer.status = true;
deferred.resolve(answer);
},
// 通讯失败的处理
function(error){
// 可以先对失败的数据集做处理,再交由controller进行处理
error.status = false;
deferred.reject(error);
});
//返回promise对象,交由controller继续处理成功、失败的业务回调
return deferred.promise;
}
}
}]);
Your getData can receive a callback function as a parameter. The parameter of this callback function is the data you want to pass. Then inject your service in your controller, and then put your other processing logic when calling the getData method of the service. Just write the callback function and pass it to the getData method. You only need to directly call the incoming callback method after processing the requested data in getData, and pass in the processed parameters.