2016-08-10 3 views
1

약속에 의해 처리 될 콜백을 호출하는 함수의 매개 변수로 전달할 수 있습니까? 예를 들어, 나는 약속 할 각도 전달 콜백

$scope.caller = function() { 
    $http({...}).then(successCallback(response) { 
     ... 
    }, function errorCallback(response) { 
     ... 
    }); 
} 

가 어떻게 약속이 완료 될 때 평가 될 $scope.caller()에 익명 함수를 전달할 수 있나요?

답변

2

매개 변수로 함수를 $ scope.caller에 전달할 수 있습니다.

$scope.caller = function (somefunc) { 
    $http(..).then(somefunc)); 
}; 
2

원하십니까?

$scope.caller = function(onFinal) { 
    $http({...}).then(successCallback(response) { 
     ... 
     onFinal(); 
    }, function errorCallback(response) { 
     ... 
     onFinal(); 
    }); 
} 
1

당신은 콜백 체인에 다른 then를 추가 할 수 있습니다

$scope.caller(function(response) { 
    ... 
}); 
0
You need to defer, resolve and return your promises in a 'Factory' or 'Services' file. 
Here is a very straightfoward way of handling promises. 
Note that '$scope.caller = function() {...}' is the same as 'function caller() {...}'. 
Always have your API calls in the 'Factories' or 'Services' file. 

Refer to example below : 

//------------------------------------------------------------------------------------ 
# caller.factory.js 
# 'app.foo.caller' refers to your directory structure i.e. app/foo/caller/caller.factory.js 

(function() { 
    'use strict'; 

    angular 
     .module('app.foo.caller', []) 
     .factory('callerSvc', CallerService); 

    /* @ngInject */ 
    function CallerService(
     $log, 
     $q, 
     $http, 
     $window, 
     $state, 
     logger, 
     session, 
     utils, 
     API_CONFIG) { 

     var ENDPOINTS = { 
      CALLERS: '/v1/callers' 
     }; 

     /** 
     * @ngdoc service 
     * @name app.foo.caller 
     * @description Caller management 
     */ 
     var service = { 
      caller: caller 
     }; 

     /** 
     * @ngdoc method 
     * @name caller 
     * @description Returns all callers 
     * @methodOf app.foo.caller 
     * @returms {promise} caller or null if not found 
     */ 
     function caller() { 
      var q = $q.defer(); 

      var request = utils.buildAuthRequest(session, 'GET', ENDPOINTS.CALLERS); 

      $http(request) 
       .success(function (callers) { 
        q.resolve(callers.result); 
       }) 
       .error(function (error) { 
        logger.error('CallerService.caller > Error ', error); 

      return q.promise; 
     } 
    } 
})(); 

//------------------------------------------------------------------------------------ 
# caller.module.js 
# 'app.foo.caller' refers to your directory structure i.e. app/foo/caller/caller.module.js 

(function() { 
    'use strict'; 

    angular 
     .module('app.foo.caller', [ 
     ]); 
})(); 
: 당신이 $scope.caller를 호출 할 때, 매개 변수로 콜백을 통과

$scope.caller = function(callback) { 
    $http({...}).then(successCallback(response) { 
     ... 
     return response; // always return in your Promise to allow chaining 
    }, function errorCallback(response) { 
     ... 
    }).then(callback); 
}