returns 多项基于来自单个 HTTP 请求的数据承诺的服务

Service which returns multiple promises based on data from single HTTP request

我希望实现具有以下功能的服务:

应存在这两个函数以提供所获取数据的不同表示。

目前我的服务概要如下:

angular.module('someApp')
.service('someService', function ($http) {

    var httpPromise = $http.get('/some/endpoint/').then(
            function(response) {
                // HTTP response data is processed
            });

    this.getSomePromise = function() {
        // Return a promise which is resolved using one representation of HTTP response
    }

    this.getAnotherPromise = function() {
        // Return a promise which is resolved using another representation of HTTP response
    }

});

如果只需要一个 'getter' 函数,那么显然我可以简单地 return 编辑 httpPromise

实现所示接口的合适方法是什么?两个或多个消费者是否可以根据同一个承诺调用 .then(),在这种情况下,我只能从两个函数中调用 return httpPromise.then(function(){...modify data...})?或者,在这种情况下,是否有必要创建一个新的承诺(使用 $q.defer())并根据保存 HTTP 响应的缓存对象以某种方式解决它?

您可以简单地在 http promise 上使用链接创建两个 promise:

var httpPromise = $http.get('/some/endpoint/');

var firstPromise = httpPromise.then(function(response) {
    return firstTransformation(response.data);
});

var secondPromise = httpPromise.then(function(response) {
    return secondTransformation(response.data);
});

this.getSomePromise = function() {
    return firstPromise;
}

this.getAnotherPromise = function() {
    return secondPromise;
}