javascript - AngularJs 在完成 2 个不同的 https 请求时调用函数

标签 javascript angularjs asynchronous angularjs-scope

假设我有 2 个 http 请求,我希望异步调用这两个请求,但我希望在渲染 View 之前完成这两个请求,我如何条件完成 2 个单独的调用才能调用一个函数。 call3 和 call4 仍在后台运行,但我不想等待它们完成。

我添加了示例代码:

var call1_done = false;
var call2_done = false;
var call3_done = false;
var call4_done = false;

API.get_client().then(function(){
    call1_done = true;
});

API.get_all_clients().then(function(){
    call2_done = true;
});

// ignore call3 and call4 they can continue in the background
if (call1_done && call2_done)
{
   render_the_page();
}

最佳答案

如果您对使用 $q.all([]) 不感兴趣,我会尝试使用 $watch

 $scope.calls = {
   call1_done: false,
   call2_done: false
 };



API.get_client().then(function(){
    $scope.calls.call1_done = true;
});

API.get_all_clients().then(function(){
    $scope.calls.call2_done = true;
});

/* 2 and 4 async tasks are running ..... */

 $scope.$watch(function () {
    return $scope.calls;
},
function (newValue, oldValue) {
    if(newValue.call1_done && newValue.call2_done ){
      render_the_page();
     }
}, true);

这里我们监听一个存储两个标志的对象,如果两个标志都变为true -> 触发render_the_page()

关于javascript - AngularJs 在完成 2 个不同的 https 请求时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20846995/

相关文章:

javascript - 单击类中包含的按钮时如何影响特定类

javascript - AngularJS中的XML到JSON(x2js)以获取HTML表

javascript - 使用 Angular.js 拆分 <input type ="text">

node.js - 在 Node.js 中,我如何使用集合作为索引以编程方式从 Redis 数据库中检索许多哈希

Javascript:在 DOM 中异步生成大表。

javascript - 为 node.js 回调实现超时

java - 未终止的字符串常量

javascript - 使用数组在 C3.js 中绘制图形

javascript - react 路由器 : How to keep logged in data (props) when re-routing

angularjs - 在测试中模拟 $routeParams 以动态更改其属性