Angularjs angular.js中的服务和控制器
这是我的控制器Angularjs angular.js中的服务和控制器,angularjs,Angularjs,这是我的控制器 app.factory('actfactory', function ($http) { var myservice = { result: [], getdata: function () { $http.get('api calll !!') .success(function (response) { console.log(response.data); myservice.resul
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 !");
});
}
};
在控制器中执行console.log()时,我得到的是空对象!
我的服务是控制台返回良好响应
如何在服务控制器中获得结果使用承诺:
app.controller("activity", function ($scope,actfactory) {
$scope.activityresult = actfactory.getdata();
console.log( $scope.activityresult);
});
此外,还应兑现您的服务承诺:
actfactory.getdata().then(function(data) {
$scope.activityresult = data;
console.log( $scope.activityresult);
});
问题在于,由于javascript是异步的,所以它不会等到
actfactory.getdata()
返回。在$scope.activityresul
get assignconsole.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 !");
});
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()
});
}
};