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

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

问题描述

我想实现我的AngularJS应用程序的诺言就像你可以在这个例子中看到: http://stackoverflow.com/a /371273分之12360882

I would like to implement promises in my AngularJS application like you can see in this example: http://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'});
    }
};

我想是能够做出的 $ HTTP GET请求,如 / API /网址ALLDATA ,然后对将被设置为 allData.projects 承诺>和客户将被设置为 allData.clients ,等一个承诺(其中 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?

推荐答案

那么,有没有太大的点的使用,你知道重新present同样的承诺2承诺。但是,你确实可以创建接收处理一个承诺服务和返回两个。事情是这样的:

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天全站免登陆