[英]AngularJS Service to Return an Object Instead of a Promise
I am trying to refactor my AngularJS code by having my service resolve a promise call that will automatically bind an object to to my scope. 我试图通过让服务解析一个将自动将对象绑定到我的作用域的promise调用来重构AngularJS代码。
// converting this:
imageService.getImages(userId)
.then(images => {
$scope.images = images;
});
// into this:
$scope.images = imageService.getImages(userId);
My current solution I am trying to refactor is: 我正在尝试重构的当前解决方案是:
function getImages(userId) {
const config = {
method: 'get',
url: '/a/images',
params: { userId: userId }
};
return $http(config).then(onGetImagesSuccess, onGetImagesError);
}
function onGetImagesSuccess(response) {
$log.info('Get image success', response);
return response.data;
}
function onGetImagesError(response) {
$log.info('Get image error', response);
}
I started playing around with $q.defer()
and I got my getImages()
to this following state. 我开始玩
$q.defer()
并将getImages()
为以下状态。 The problem is that I imageService.getImages()
returns a Promise instead of the images. 问题是我
imageService.getImages()
返回Promise而不是图像。 It is interesting that the list of images do get logged tho. 有趣的是,图像列表确实被记录下来了。
function getImages(userId) {
const deferred = $q.defer();
const config = {
method: 'get',
url: '/a/images',
params: { userId: userId }
};
let call = $http(config).then(onGetImagesSuccess, onGetImagesError);
deferred.resolve(call);
return deferred.promise.then(images => {
$log.info(images); // List of images does get logged
return images; // Promise gets returned instead of the actual images
});
}
I am wondering what do I need to do to refactor my code to get my imageService.getImages()
to return a list of images instead of a Promise. 我想知道我该怎么做才能重构代码以使
imageService.getImages()
返回图像列表而不是Promise。
This can be done by same recipe that is used in $resource
. 这可以通过
$resource
使用的相同配方来完成。 Empty object (array) is returned which is filled with data asynchronously. 返回空对象(数组),该对象异步填充数据。 A promise should be returned as well, in case there's a need to know when and how a request finished:
如果需要知道何时以及如何完成请求,还应该返回一个Promise:
var result = {
data: [],
promise: $http(...).then(response => {
return Object.assign(result.data, response.data);
})
};
return result;
Then imageService.data
array is bound in view. 然后,将
imageService.data
数组绑定到视图中。
This pattern has its pros and cons. 这种模式各有利弊。 It is natural to have
then
in controller to unwrap promises. then
自然而然地让控制者解开承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.