【问题标题】:Multiple HTTP requests in AngularAngular 中的多个 HTTP 请求
【发布时间】:2015-07-16 01:27:24
【问题描述】:

所以这是我的控制器:

app.controller('dbCtrl', function($scope, $http) {
$http.get("http://private-abc.apiary-mock.com/bus")
.success(function(response) {
 $scope.network = response.networkupdates;});
 });

接下来我想做的是调用第二个 HTTP 请求,我想就最佳实践而言,最好是创建一个第二个控制器来调用第二个 HTTP,还是最好在此包含第二个 HTTP 调用当前控制器(如果是,如何?) 谢谢。

【问题讨论】:

标签: javascript angularjs rest


【解决方案1】:

因此,使用 Promise 的一个很酷的方面是它们可以被链接。所以在你的情况下,你打电话:

$http.get("http://private-abc.apiary-mock.com/bus")

它返回一个承诺,然后您可以像这样链接到另一个承诺:

var requests = $http.get("http://private-abc.apiary-mock.com/bus").then(function(response) {
    $scope.network = response.networkupdates;
    // make second get call and return it to chain the promises
    return $http.get("some-other-endpoint").then(function(otherResponse) {
        // you can do something here with the response data
        return otherResponse;
    });
});

您现在拥有的是两个将返回最终值的链式 Promise,因此如果您稍后调用它:

requests.then(function(otherResponse) {
    // or you can do something here
    doSomething(otherResponse);
});

就 Angular 的最佳实践而言,我想说你最好创建一个服务或工厂来处理任何和所有 http 请求。控制器实际上只是将数据绑定到视图;服务是您的业务逻辑和数据填充应该发生的地方。

【讨论】:

  • 甚至不清楚这些调用是相互关联的,甚至需要被链接起来
【解决方案2】:

您可以在同一个控制器中进行$http 调用。

$http 服务是一个函数,它接受一个参数——一个配置对象——用于生成一个 HTTP 请求并返回一个带有两个 $http 特定方法的promisesuccess and error。它在内部使用 $q(受 Kris Kowal 的 Q 启发的 promise/deferred 实现)。

如果您的两个$http 彼此独立,您可以使用$q.all 来“加入”您的http 调用的结果。

例子:

$q.all([
    $http.get("http://private-abc.apiary-mock.com/bus"),
    $http.get('/someUrl')
  ]).then(function(results) {
     $scope.network = results[0];
     $scope.whatevername= results[1]

  });
}

如果您的 http 调用相互依赖,那么您可以使用 chaining 的概念。

例如:

$http.get("http://private-abc.apiary-mock.com/bus").then(function(result) {
    $scope.network = result.networkupdates;    
    return $http.get("someurl").then(function(res) {        
        return res;
    });
});

q的参考可以看https://github.com/kriskowal/q

$q service的参考可以看https://docs.angularjs.org/api/ng/service/$q

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    相关资源
    最近更新 更多