首页 \ 问答 \ Angular JS异步两个API请求(Angular JS async two API requests)

Angular JS异步两个API请求(Angular JS async two API requests)

在Angular中,我现在有这样的:

app.factory("myService", function($http, $q) {
    return {
        doBoth: function(data) {
            return $q.all([$http.post("/search/local", data), $http.post("/search/shape", data)]);
        }
    };
});

我称之为:

$scope.$on("localSearch", function(event, data) {
    return myService.doBoth(data);
});

但是,我不认为它是异步发生的。 他们都需要花费很长时间才能完成,所以我需要Angular同时请求两者,所以完整的请求不是一个+另一个 - 但是他们都返回的最快时间。


In Angular at the moment I have this:

app.factory("myService", function($http, $q) {
    return {
        doBoth: function(data) {
            return $q.all([$http.post("/search/local", data), $http.post("/search/shape", data)]);
        }
    };
});

and i call it like this:

$scope.$on("localSearch", function(event, data) {
    return myService.doBoth(data);
});

However I do not think it is happening asynchronously. They both take quite a time to get fulfilled so I need Angular to request both at the same time, so the complete request isn't one + the other - but the quickest time they both get returned in.


原文:https://stackoverflow.com/questions/15437520
更新时间:2021-06-06 08:06

最满意答案

如果要在两个查询完成后触发回调,请将其放在$q.then()方法中。

$scope.$on("localSearch", function(event, data) {
  return myService
    .doBoth(data)
    .then(function (response) {
      // both deffered completed
    });
});

我在这里创建了示例http://plnkr.co/edit/7G8oFMSx8cPC98zDhlNq?p=preview


If you want to fire callback after both queries completed, place it in $q.then() method.

$scope.$on("localSearch", function(event, data) {
  return myService
    .doBoth(data)
    .then(function (response) {
      // both deffered completed
    });
});

I've created sample here http://plnkr.co/edit/7G8oFMSx8cPC98zDhlNq?p=preview

相关问答

更多

如何在Angular2循环/映射中执行异步HTTP请求并修改原始循环数组?(How to do a async HTTP request inside an Angular2 loop/map and modify the original loop array?)

// You need to set up a subject in your sevice private _videoObject = new Subject < any > (); videoDataAnnounced$ = this._videoObject; let url = [YouTube API V3 list url] let detailUrl = 'https://www.googleapis.com/youtube/v3/videos?part=contentDeta ...

CORS Angular JS(CORS Angular JS)

是的。 如果您无法在服务器上启用cors标头,那么您唯一能做的就是从nodejs或任何其他类型的服务器访问服务器。 如果你最终计划在cordova中运行你的角度,你可以直接$ http请求,因为cordova不会阻止corsable请求。 Yes it is. If you can't enable cors headers on the server then the only thing you can do is access the server from your nodejs or a ...

Angular JS异步两个API请求(Angular JS async two API requests)

如果要在两个查询完成后触发回调,请将其放在$q.then()方法中。 $scope.$on("localSearch", function(event, data) { return myService .doBoth(data) .then(function (response) { // both deffered completed }); }); 我在这里创建了示例http://plnkr.co/edit/7G8oFMSx8cPC98zDhlNq? ...

使用sinatra流API的异步请求(async requests using sinatra streaming API)

回答我自己的问题: require 'em-hiredis' require 'sinatra/base' class App < Sinatra::Base def redis @redis ||= EM::Hiredis.connect end get '/' do stream :keep_open do |out| redis.blpop('abcdef', 15).callback do |x| out << "x=#{x}" ...

如何等待异步HTTP请求在Angular 4上返回值?(How to wait for async HTTP requests to return values on Angular 4?)

您应该在getData()方法中返回observable,然后在您的组件中订阅。 这样组件知道observable何时完成(在订阅方法中)。 // card.service.ts getData() { return Observable.forkJoin(...); } // cards.component.ts this._cardsService.getData().subscribe(data => { this.charts = ...; }); You should ...

Async.js和Angular 2(Async.js and Angular 2)

你可以使用它,如果你想,只需安装npm i @types/async , npm i async和导入库: import async from 'async'; You can use it if you want, just install typings npm i @types/async, npm i async and import library: import async from 'async';

使用REST API的Angular JS App(Angular JS App using REST API)

我追溯了你正在使用的服务器,发现了一个名为ngFrame的项目,它几乎消耗了Drywall所有API,还有一些认证样本。 您可以在源代码中看到一个名为setAuthHeader的函数: function setAuthHeader(user) { $http.defaults.headers.common['Authorization'] = user.authHeader } 这里传递的用法来自帖子对登录的响应: $http.post('/api/login', user).succe ...

异步请求进入for循环angular.js(Async request into for loop angular.js)

您可以通过将promises链接在一起来使用$q来创建类似的需求。 例如: var chain = $q.when(); angular.forEach(myArr, function(item){ chain = chain.then(function(){ var data = { myQuery: item.query }; return $http.post('/myServiceUrl', data).suc ...

使用Google Feed API的Angular JS - 奇怪的行为(Angular JS with Google Feed API - strange behaviour)

在项目循环结束后,回调函数异步执行。 在循环结束时, i等于2,因为你的items数组中有2个items 。 看看Javascript臭名昭着的循环问题? 有关相同行为的另一个示例,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake以获得更深入的解释。 The callback function is exec ...

Angular.JS中的Async typeahead不显示选项(Async typeahead in Angular.JS do not show options)

typeahead适用于输入元素。 当输入松散焦点时,ui-boostrap-tpls.js不像@kir那样执行代码的某些部分。 如果你有一个从自动完成输入中删除焦点的指令,或者你有一个微调器组件在执行AJAX请求时显示一个图标,它可能会从自动完成输入中夺走焦点。 在我的特定情况下,我使用angular-block-ui,我修复了这种情况,从阻塞中删除了阻塞行为: // Tell the blockUI service to ignore certain requests blockUIConfi ...

相关文章

更多

最新问答

更多
  • 如何从远程文件拉取文件而不覆盖本地文件?(How do I pull files from remote without overwriting local files?)
  • Reactjs:状态改变时重新渲染iframe(Reactjs: re-renders iframes when state changed)
  • 奇怪的网址,以及跟随php页面流程的困难(odd url, and difficulty in following the php page flow)
  • 标签活动无效(Tab Activity is not working)
  • JavaME合适的语法编译器建议?(JavaME-suitable grammar compiler recommendations?)
  • 指定参数(Specifying arguments)
  • 可以通过Ruby插件或控制台覆盖Sketchup中的键盘快捷键吗?(Can one override keyboard shortcuts in Sketchup through the a Ruby Plugin or Console?)
  • 计算Java EE Web App中用户数的最佳方法(Best way to count number of users in a Java EE web App)
  • 无法使用templateUrl加载cordova中的外部模板(unable to load external templates in cordova with templateUrl)
  • PHPExcel:写入期间无法使用缓存(PHPExcel: Unable to use cache during write)
  • 在javascript中嵌套这个指针(nested this pointer in javascript)
  • 谁跟领航致远培训过,有问题问下啊
  • 控制器要求在入门时下载(Controller ask to download on entry)
  • 未能通过conda安装Asyncio(Failure to install Asyncio via conda)
  • 如何查找已完成项目的总长度?(How to find length of total completed items?)
  • 如何检查OleInitialize是否已被调用?(How to check if OleInitialize has already been called?)
  • SQL在特定范围内返回列中具有最大值的行(SQL Returning rows with max value in column, within a specific range)
  • preg_match从url获取id(preg_match get the id from url)
  • 如何在运算符中为make方程转换perl变量?(How to convert a perl variable in a operator for make equations?)
  • 在导航上方添加空格/标题。(Add a white space/ header above navigation.)
  • MeetingItem已保存;(MeetingItem saved; but change now shown in Calendar)
  • c#vb:我们应该使用System.Lazy进行资源密集型任务吗?(c# vb: Should we use System.Lazy for resource-intensive task? (when threading is not needed))
  • 为什么在armeabi代码中使用armeabi-v7a代码?(Why use armeabi-v7a code over armeabi code?)
  • 获取请求的自定义标头(Java HTTP)(Fetching a custom header of a request (Java HTTP))
  • 是否可以在嵌套的if语句中从varchar转换为numeric以动态评估参数?(Is it possible to convert from varchar to numeric within a nested if statement in order to dynamically evaluate a parameter?)
  • 如何将Html.ActionLink转换为链接到Ajax调用的按钮?(How to convert from Html.ActionLink to a button linked to Ajax call?)
  • 应用程序如何处理Windows符号链接?(How are Windows symbolic links treated by the apps?)
  • html,js,css在jsfiddle中工作,但不在sharepoint中(html, js, css works in jsfiddle but not in sharepoint)
  • 从Ruby脚本调用Elasticsearch Rest API(Calling Elasticsearch Rest API from Ruby script)
  • 如何将嵌套setTimeouts转换为承诺(How to convert nested setTimeouts to promises)