链接angularjs rest端点访问

Chaining angularjs rest endpoint access

本文关键字:访问 端点 rest angularjs 链接      更新时间:2023-09-26

为了尝试按顺序运行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请求链:https://tutorialedge.net/angularjs-promises-tutorial

将其包装在超时函数中基本上是错误的方法。正如你所说,这些承诺"极有可能"一个接一个地出现。看看那篇文章的链接承诺部分,你会看到如何保证顺序执行!

下面是那篇文章的代码示例摘录!

// 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;
  });