简体   繁体   English

AngularJS服务返回一个对象而不是一个承诺

[英]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.

相关问题 在AngularJS服务中缓存一个Promise对象 - Caching a promise object in AngularJS service AngularJS服务返回数据而不是Promise - AngularJS Service returning data instead of promise AngularJS服务-使$ resource立即返回数据而不是一个承诺,因此客户端不必使用.then() - AngularJS Service - Make $resource return data right away instead of a promise so clients don't have to use .then() angularjs:链承诺返回一个承诺而不是对象 - angularjs: chain promises returns a promise instead of an object 角度js-返回promise代替数据对象 - angular js - Return promise instead data object Firestore 返回 True 或 False 而不是 Promise Object - Firestore Return True or False instead of the Promise Object 如何让 axios 返回 object 而不是 promise - how to get axios to return the object instead of promise AngularJS异步请求方法服务使用Promise返回数据 - AngularJS Async request method service return data using promise 在spyOn服务的Promise中获取函数返回值-Jasmine Angularjs - Get function return value inside promise on spyOn service - Jasmine Angularjs AngularJS-您是否从服务/工厂返回承诺或数据? - AngularJS - Do you return the promise or data from the service/factory?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM