您好,我的服务代码是:
angular.module('lucho1App').factory('ApiExample', ['$http', '$q', function($http, $q) {
return {
promiseToHaveData: function() {
return $http.get('http://data.colorado.gov/resource/4ykn-tg5h.json').then(function(response) {
var result = response.data;
console.log(result);
return result;
}, function(response) {
console.log('Error has ocurred');
});
}
};
}]);
我的 Controller 是:
angular.module('lucho1App')
.controller('MainCtrl',['$scope', 'ApiExample',function MainCtrl($scope,ApiExample) {
$scope.apiExampl=ApiExample.promiseToHaveData();
console.log($scope.apiExampl);
}]);
服务中的console.log显示输出,这意味着我的请求成功,但在 Controller 中$scope.apiExampl
未定义我的错误在哪里?
最佳答案
Promise 是异步的,因此它会在稍后解决,并且 then 中的函数将在那一刻被调用。回调中的返回允许更改传递给下一个 then 调用的对象,因为 Promise 是可链接的对象。
首先,您必须在服务中返回 Promise 对象:
return $http.get(...);
第二次更改您的 Controller ,如下所示:
ApiExample.promiseToHaveData().then(function(data){
$scope.apiExampl=data;
});
请注意,我在这里执行=data
,因为在您的服务中,您已经从响应
中提取了数据对象
关于javascript - Controller AngularJs 中的服务注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37658565/