今天我有一个我真的不明白的问题:)
我编写了一个调用我的 api 的 Angular 服务,重新格式化结果并将此数据带到 Angular Controller 中的另一个函数。 我这样做了很多次,但今天出了点问题。
重新格式化的结果和 Controller 访问的数据不一样,我不知道(也许理解)为什么 :D
这是服务代码:
myApp.factory('apiService', function($http) {
var myService = {
getMunicipalityAsync : function(id) {
var promise = null;
promise = $http({
method: 'GET',
url: '/api2/cc/municipality/' + id
}).success(function(response) {
var r = {
'success': true,
'data': response.data
};
console.debug(r, 'return this');
return r;
}).error(function(data, status, headers, config) {
logError("[apiService], getMunicipalityAsync() error, with status: " + status);
});
return promise;
}
}
return myService;
});
这是 Angular Controller 的代码。
apiService.getMunicipalityAsync($scope.conf.geoarea).then(
function( d ) {
console.debug( d, 'return from service');
}, function( error ) {
alert('error');
});
调试数据不一样:(
谢谢!
最佳答案
这两个方法 success 和 error 是 $http 的特定方法,如文档中所述: http://docs.angularjs.org/api/ng .$http
success 和 error 这些方法有 4 个参数:data、status、headers 和 config。但是普通的 promise 方法只会得到一个对象作为结果。 在您的代码中,您实际上可以看到在 getMunicipalityAsync 的 then-function 中获得的参数“d”包含属性数据、状态、 header 和配置。 文档中也明确提到了这一点:
“由于调用$http函数的返回值是一个promise,你也可以使用then方法注册回调,这些回调将接收一个参数——一个代表响应的对象。见API签名和类型下面的信息了解更多详情。”
apiService.getMunicipalityAsync($scope.conf.geoarea).then(
function( d ) {
console.debug( d.data, 'return from service');
}, function( error ) {
alert('error');
});
但我认为你有一个误解。如果你想在你的 Controller 中访问增强数据,那么你必须创建一个新的 promise ,你需要在成功方法中用你的增强数据“解决”:
myApp.factory('apiService', function($http, $q) {
var myService = {
getMunicipalityAsync : function() {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'http://192.168.1.151/temp/angulartest/data/data.json'
}).success(function(response) {
var result = {
'success': true,
'data': response.data
};
console.debug(result, 'return this');
deferred.resolve(result);
}).error(function(data, status, headers, config) {
logError("[apiService], getMunicipalityAsync() error, with status: " + status);
deferred.reject();
});
return deferred.promise;
}
}
return myService;
});
然后您实际上可以直接在您的 Controller 中访问增强数据:
apiService.getMunicipalityAsync().then(
function(enhancedData) {
console.debug(enhancedData, 'return from service');
}, function(error) {
alert('error');
});
关于javascript - Angular 、 promise 和异步功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17295009/