如何为这项服务编写控制器?

时间:2015-01-28 10:38:11

标签: angularjs callback angularjs-service

myapp.factory('serviceName', function( $http, webStorage){

    var factory = {};
    var resoureurlBase=some base url;

    factory.genericService = function(method, payload, methodName, callbackFn, callbackError, param) {

            var httpRequest = null;
            if (param && param == true) {
                httpRequest = $http({
                    url: resoureurlBase+methodName,
                    method: method,
                    params: payload,
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
            } else {
                httpRequest = $http({
                    url: resoureurlBase+methodName,
                    method: method,
                    data: payload,
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                });
            }

            httpRequest.then(function(response) {
                    if (callbackFn && callbackFn.call) {
                        callbackFn.call(null, response);
                    }
                },
                function(response) {
                    if (callbackError && callbackError.call) {
                        callbackError.call(response);
                    }
                });
            httpRequest.error(function(data, status, headers, config) {

            });
        };
        return factory;
});

/ * 我上面写的服务如何在控制器中处理 我的意思是 如何在控制器中编写回调函数 怎么注射 等。

* /

2 个答案:

答案 0 :(得分:0)

简单DI(依赖注入)到你的控制器: -

myapp.controller('myCtrl',['$scope','serviceName',function($scope,serviceName){

// use serviceName to call your factory function
}]);

参考: - https://docs.angularjs.org/guide/di

答案 1 :(得分:0)

您需要调用

之类的服务
serviceName.genericService(--parmas--).then(function(d){
//success
}) 

因为来自服务serviceName,您只需要使用.then返回需要解决的承诺。

控制器

var mainController = function($scope, serviceName) {
  var callbackFn = function() {
  console.log('Success');
  }
  var callbackError = function() {
  console.log('Error');
  }

  var parameter = {
      param1: 1
  },
  method = 'something', payload = 100, methodName = 'something';
  serviceName.genericService(method, payload, methodName, callbackFn, callbackError, parameter).then(
    //success function
    function(data) {
        //call after call succeed
    },
    //error function
    function(error) {
        //call after call error 
    });
};

myapp.controller('mainController', ['$scope', 'serviceName', mainController()];

希望这可以帮到你。感谢。