[英][AngularJS][Ionic] Make Controller wait for Service that uses another $http service
问题是Controller不会等待使用另一个$ http服务的Service,而我没有得到任何数据。
services.js:
angular.module('starter.services', [])
.factory('Likes', function ($http) {
var likes;
$http.get("http://localhost:8100/js/offers.json")
.success(function (results) {
likes = results.offers;
console.log("ok!");
})
.error(function (results) {
console.log("error");
});
return {
all: function () {
return likes;
},
get: function (likeId) {
for (var i = 0; i < likes.length; i++) {
if (likes[i].id === parseInt(likeId)) {
return likes[i];
}
}
return null;
}
};
})
controllers.js(部分):
.controller('OneCtrl', function($scope, $stateParams, Likes) {
$scope.offer = Likes.get($stateParams.likedId);
})
.controller('LikedCtrl', function($scope, $stateParams, $http, Likes) {
$scope.liked = Likes.all();
})
我已经阅读了有关promises,async(),callbacks和$ q的文章和主题,但我不知道如何在我的代码中集成这些东西,尽管经过多次尝试。
退还您服务的承诺:
angular.module('starter.services', [])
.factory('Likes', function ($http) {
// likes is a promise of array of likes
var likes = $http.get("http://localhost:8100/js/offers.json")
// then allows transforming the promise of http response into a promise of something else
.then(function(response) {
// transforms the http response into an array of likes
return response.data.offers;
});
return {
// all returns a promise of array of likes
all: function () {
return likes;
},
// get returns a promise of like
get: function (likeId) {
// then allows transforming a promise of array of likes into a promise of something else
return likes.then(function(likes) {
// transform the array of likes into a single like
for (var i = 0; i < likes.length; i++) {
if (likes[i].id === parseInt(likeId)) {
return likes[i];
}
}
return null;
}
}
};
});
并在控制器中
.controller('OneCtrl', function($scope, $stateParams, Likes) {
Likes.get($stateParams.likedId).then(function(like) {
$scope.offer = like;
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.