//Load Property Types
$scope.getAddressByPostcode = function() {
PostCodeLookup.getAddress(function(postCodeAddress,'NN4 5DT') {
$scope.postCodeAddress = postCodeAddress;
console.log($scope.postCodeAddress);
});
};
我的控制器中有上面的代码。 以下是我在Angular Factory中的内容
'use strict';
angular.module('core').factory('PostCodeLookup', ['$http', function($http) {
var apService = 'https://api.postcodes.io';
function getAddressByPostcode(callback,postcode) {
$http({
method: 'GET',
url: apService+ '/postcodes/'+postcode,
cache: true
}).success(callback);
}
return {
getAddress: getAddressByPostcode
};
}]);
我遇到问题,将参数传递给我的getAddressByPostcode以及回调。
angular不会处理params的回调。
答案 0 :(得分:0)
看起来您的代码应该是这样的:
$scope.getAddressByPostcode = function() {
PostCodeLookup.getAddress(function(postCodeAddress) {
$scope.postCodeAddress = postCodeAddress;
console.log($scope.postCodeAddress);
},'NN4 5DT');
};
请注意邮政编码参数的放置。
正如@Martijn建议的那样,更好的解决方案是从工厂函数中返回一个承诺:
function getAddressByPostcode(postcode) {
return $http({
method: 'GET',
url: apService+ '/postcodes/'+postcode,
cache: true
});
}
return {
getAddress: getAddressByPostcode
};
然后像这样使用它:
PostCodeLookup.getAddress('NN4 5DT').then(function(result) {
$scope.postCodeAddress = result.data;
console.log($scope.postCodeAddress);
});
答案 1 :(得分:0)
也许这段代码片段有助于使用带参数的回调:
创建一个回调对象:
function createCallback(p_context, p_function, p_params) {
if(angular.isFunction(p_function)) {
var callback = {
'context': p_context,
'function': p_function,
'params': p_params
};
return callback;
} else {
logger.error('createCallback(context, function, params): function not defined');
}
}
执行回调:
function executeCallback(p_cb) {
var callback = p_cb;
cb['function'].call(cb['context'], cb['params']);
}
将其包装在服务中,它是可重复使用的......
电贺 基督教