gpt4 book ai didi

javascript - Angular 中的多个 HTTP 请求

转载 作者:行者123 更新时间:2023-11-28 07:09:20 26 4
gpt4 key购买 nike

这是我的 Controller :

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

接下来我想做的是调用第二个 HTTP 请求,我想就最佳实践而言,最好创建第二个 Controller 来调用第二个 HTTP,或者最好在其中包含第二个 HTTP 调用当前 Controller (如果是,如何?)谢谢。

最佳答案

因此,使用 Promise 的一个很酷的方面是它们可以被链接起来。因此,就您而言,您正在调用:

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

它返回一个 promise ,然后您可以将其链接到另一个 promise ,如下所示:

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 请求。 Controller 实际上只是将数据绑定(bind)到 View ;服务是您的业务逻辑和数据填充应该发生的地方。

关于javascript - Angular 中的多个 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31443937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com