来自 AngularJS 中单个 $http 请求的多个承诺 [英] Multiple promises from single $http request in AngularJS

查看:27
本文介绍了来自 AngularJS 中单个 $http 请求的多个承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 AngularJS 应用程序中实现 promises,就像你在这个例子中看到的一样:https://stackoverflow.com/a/12360882/371273

I would like to implement promises in my AngularJS application like you can see in this example: https://stackoverflow.com/a/12360882/371273

我的应用程序将获取多个数据数组,从而在我的服务器上进行多次数据库访问,但我已将我的服务器配置为将所有这些数据作为一个响应返回,以尽量减少请求以保持我的应用程序尽可能高效(除非所有数据到达客户端,否则数据基本上是无用的).所以,而不是这样做...

My application will take multiple arrays of data making multiple database hits on my server, but I have configured my server to return all of that data as one response in the idea of minimizing requests to keep my application as efficient as possible (the data is essentially useless unless all of the data gets to the client). So instead of doing this...

MyCtrl.resolve = {
    projects : function($q, $http) {
        return $http.get('/api/projects'});
    },
    clients : function($q, $http) {
        return $http.get('/api/clients'});
    }
};

我希望能够对像 /api/allData 这样的 URL 发出 single $http GET 请求,然后有projects 的承诺将设置为等于 allData.projectsclients 的承诺将设置为等于 allData.客户端等(其中allData是我的单个请求返回的数据).我对承诺还是很陌生,有人能给我一个例子来说明我如何在 MyCtrl.resolve 中设置这些承诺吗?

I would like to be able to make a single $http GET request to a URL like /api/allData, and then have a promise for projects that will be set equal to allData.projects and a promise for clients that will be set equal to allData.clients, etc. (where allData is the data that came back with my single request). I'm still very new to promises, can someone give me an example of how I would set up these promises inside MyCtrl.resolve?

推荐答案

嗯,使用两个你知道代表同一个承诺的承诺并没有多大意义.但是您确实可以创建一个接收处理一个承诺并返回两个承诺的服务.像这样:

Well, there is not much of a point in using two promises that you know represent the same promise. But you could indeed create a service that receive handles the one promise and return two. Something like this:

var mod = angular.module('mod', []);
mod.service('theService', function($q, $http) {
  return function() {
    var cliDeferred = $q.defer(),
        proDeferred = $q.defer();

    $http.doYourStuff().then(function _onSuccess(data) {
      cliDeferred.resolve(data.clients);
      proDeferred.resolve(data.projects);
    }, function _onError(err) {
      cliDeferred.reject(err);
      proDeferred.reject(err);
    });

    return {clients: cliDeffered.promise, projects: proDeferred.promise};
  };
});

但正如我所说,这没有多大意义.也许更好的解决方案,考虑到您的服务将返回一个数组,将返回一个带有空数组的对象,并在 $http 承诺完成时填充它们.

But as I said, there is not much of a point in this. Maybe a better solution, considering your service will return an array, would be return an object with empty arrays and fill them when the $http promise gets completed.

这篇关于来自 AngularJS 中单个 $http 请求的多个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆