角度嵌套 GET

Angular nested GETs

本文关键字:GET 嵌套      更新时间:2023-09-26

我有一个有趣的情况,我从一个 GET 请求中获取一个 id 列表,然后我想抓取第一个并执行另一个 GET 请求以获取该对象的图像 URL。不幸的是,有时从第一个 GET 请求返回的 ID 无效,我们需要检查下一个 ID。我目前正在尝试一些递归回调方法来执行此操作,但这并没有做我想要的,而且由于 Angular 的异步性质,我只是没有得到任何结果。

这是我的代码示例:

app.controller('gr_menu', function($scope, grAPI, flashManager, catalogAPI) {
$scope.reports = [];
grAPI.ReportList().then(
  function(success) {
    success.data.forEach(function(report) {
      if(report.live) {
        $scope.reports.concat({'id': report.id, 'title': report.game, 'imgUrl': getReportData(report)});
      }
    });
  },
  function(error) {
    flashManager.flashMessage('Danger', 'Failed to load game reports: '+error);
  });
function getReportData(report) {
  catalogAPI.SearchGame(report.game, [{"json.offerType":"Base Game"}])
    .then(function(success){
      var i = 0;
      return checkOfferID(success.data.result[i].offerId, function (result) {
        i++;
        console.log(result)
        if (result != false) {
          return checkOfferID(success.data.result[i].offerType);
        } else {
          return result;
        }
      });
    });
}
function checkOfferID(offerID) {
  Origin.games.catalogInfo(offerID)
    .then(function (catData) {
      return catData.customAttributes.imageServer + catData.localizableAttributes.packArtLarge;
    }, function (catErr) {
      return false;
    });
  }
});

所以它实际上是 3 个 GET 请求深度。首先是获取我们的"报告"列表,然后从那里获取这些报告中指示的游戏的ID,然后从那里获取图像。

我从该控制台中没有得到任何东西.log所以也许我误解了该回调应该如何工作。我仍在尝试熟悉使用 Angular 和回调。如果是 python,我会通过一个简单的 for 循环和中断来实现这一点。

我无法真正理解您的代码(我也在使用 angularJS 迈出了第一步(,但我认为您想要类似于以下"app.js"的东西(使用带有控制器和服务的模块的简单示例(:

angular.module('testApp', [])
  .controller('TestCtrl', ['$log','TestService',
      function($log, TestService) {
        var self = this;
        TestService.getUserList().then(function (ld) {
          TestService.getUserInfo().then(function(ud){
            //$log.log(ud.data.args.url);
            self.photo_url = ud.data.args.url;
          })
        });
  }])
  .factory('TestService', ['$log', '$http', function($log, $http) {
    return {
      getUserList: function() {
        return $http.get('https://httpbin.org/get?list=[{id:1,%20name:%20%22jhon%22},{id:2,%20name:%22Lewis%22}]')
      },
      getUserInfo: function() {
        return $http.get('https://httpbin.org/get?id=1&name=jhon&url=https://www.gravatar.com/avatar/346173670fc42829e26d7965cbc5c3e0')
     }
    };
  }]);

然后你可以将"photo_url"值绑定到 HTML,类似于 (index.html(:

<html ng-app="testApp">
    <body ng-controller="TestCtrl as testCtrl">
      <img ng-src='{{testCtrl.photo_url}}' alt="something kwel"/>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.js">
        </script>
        <script src="app.js"></script>
    </body>
</html>

希望已经了解了你想要什么,并希望这对你也有帮助。

注意:使用来自 http bin 的模拟网址进行测试。