服务和控制器angular.js
问题描述:
app.factory('actfactory', function ($http) {
var myservice = {
result: [],
getdata: function() {
$http.get('api calll !!')
.success(function (response) {
console.log(response.data);
myservice.result.push(response.data);
}).error(function() {
if (window.localStorage.getItem("activity") !== undefined) {
self.results.push(JSON.parse(window.localStorage.getItem("activity")));
}
alert("please check your internet connection for updates !");
});
}
};
这是我的控制器服务和控制器angular.js
app.controller("activity", function ($scope,actfactory) {
$scope.activityresult = actfactory.getdata();
console.log($scope.activityresult);
});
虽然控制器做的console.log()在我得到空的对象! 和我的服务是控制台返回罚款响应?
如何获得的结果在服务
答
问题是因为javascript是异步的,它不会等到actfactory.getdata()
返回。在$scope.activityresul
得到分配console.log($scope.activityresult);
将执行。解决方法是使用回调并等待,直到出厂退货
app.controller("activity", function ($scope,actfactory) {
$scope.activityresult = actfactory.getdata(function(){
console.log($scope.activityresult);
});
});
app.factory('actfactory', function ($http) {
var myservice = {
result: [],
getdata: function (callback) {
$http.get('api calll !!')
.success(function (response) {
console.log(response.data);
myservice.result.push(response.data);
callback()
}).error(function() {
if (window.localStorage.getItem("activity") !== undefined) {
self.results.push(JSON.parse(window.localStorage.getItem("activity")));
}
alert("please check your internet connection for updates !");
callback()
});
}
};
答
使用承诺的控制器:
actfactory.getdata().then(function(data) {
$scope.activityresult = data;
console.log($scope.activityresult);
});
另外,从服务返回一个承诺:
return $http.get('api calll !!')
.success(function (response) {
console.log(response.data);
myservice.result.push(response.data);
return response.data;
}).error(function() {
if (window.localStorage.getItem("activity") !== undefined) {
self.results.push(JSON.parse(window.localStorage.getItem("activity")));
}
alert("please check your internet connection for updates !");
});