Javascript 链接angularjs rest端点访问

Javascript 链接angularjs rest端点访问,javascript,angularjs,Javascript,Angularjs,要尝试按顺序运行angularjs rest,我将初始函数延迟1秒,将下一个函数延迟2秒: setTimeout(function () { $http.get("/rest1") .then(function(response) { $scope.val1 = response.data; }); }, 1000) setTimeout(function () { $http.get("/rest2") .then(function(response)

要尝试按顺序运行angularjs rest,我将初始函数延迟1秒,将下一个函数延迟2秒:

  setTimeout(function () {
  $http.get("/rest1")
  .then(function(response) {
      $scope.val1 = response.data;
  });
}, 1000)

  setTimeout(function () {
  $http.get("/rest2")
  .then(function(response) {
      $scope.val2 = response.data;
  });
}, 2000)
这种方法有问题,因为它不能保证第二个
rest
函数将在第一个函数之后运行(尽管很有可能)


这些
rest
调用是否可以链接,以保证
rest1
rest2
之后执行?

我的最新教程之一介绍了这种http请求链接:

用超时函数包装它基本上是错误的。正如你所说,这些承诺很可能会一个接一个地兑现。看看那篇文章的链接承诺部分,你会看到如何保证顺序执行

下面是该帖子的代码示例摘录

// first chop our 
$http.get('api/chop/onions')
  .then(function success(response){
    // once that is done chop our carrots
    return $http.get('api/chop/carrots');
  })
  .then(function success(response){
    // once the carrots are done, add both to the stew
    return $http.get('api/add/onionsAndCarrots');
  })
  .then(function success(response){
    // serve our stew
  });

绝对不要在时间不可预测的事情上使用计时器

使用承诺链,例如:

$http.get("/rest1")
  .then((rest1Data) => {
    $scope.val1 = rest1Data.data;
  })
  .then(() => {
    return $http.get('/rest2');
  }).
  .then((rest2Data) => {
    $scope.val2 = rest2Data.data;
  });

不清楚什么是关系。它们都覆盖了同一个范围变量,而第二个变量似乎并不依赖于第一个变量的数据。您只需添加另一个
。然后
,并在其中进行第二次调用。@charlietfl question updated,thankslink only答案在这里没有什么价值。链接和答案是不容易审查的背景下,其他答案。提供相关代码,并仅使用链接作为问题的支持。应分配每个响应的数据属性object@charlietfl完全正确,修正了。