angular.js - Layered design and coding of Controller and Service in AngularJS
黄舟
黄舟 2017-05-15 17:08:29
0
1
574

Recently, I saw that data processing in the controller is not very suitable, so I went to learn the hierarchical design and coding of Controller and Service. I referred to http://www.jianshu.com/p/1e1a... , but one problem I encountered during use is that when the Service layer handles communication callbacks and passes the business callbacks to the Controller layer to call the $http service, how do I pass the request parameters? The code is as follows:

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;
    }
}
}]);
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
PHPzhong

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.


angular.module('demo')
.service('myService',['$http','$q',function($http,$q){
return {
    getData:function(callback){
        var deferred = $q.defer();
        var promise = $http.get("xxx");
         promise.then(
                  // 通讯成功的处理
                  function(answer){
                    //在这里可以对返回的数据集做一定的处理,再交由controller进行处理
                    answer.status = true;
                    deferred.resolve(answer);
                    ...//处理数据,得到data
                    callback&&callback(data);
                  },
                  // 通讯失败的处理
                  function(error){
                    // 可以先对失败的数据集做处理,再交由controller进行处理
                    error.status = false;
                    deferred.reject(error);
                  });
                //返回promise对象,交由controller继续处理成功、失败的业务回调
        return deferred.promise;
    }
}
}]);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template