簡體   English   中英

通過AngularJS中的控制器將結果從一個工廠/服務ajax方法傳遞給另一個工廠/服務ajax方法

[英]Pass results from one factory/service ajax method to another via the controller in AngularJS

我在服務中有兩個ajax調用; 第一個, AjaxOnefields (用戶輸入)獲取我想要的數據,然后我想通過將其傳遞給另一個ajax調用來改變數據, AjaxTwo以獲得我需要的結果。 兩個ajax調用都是完全不同的服務,並且可以由多個控制器進行交互,因此我已經將它們置於他們自己獨特的Angular factory方法中(可以是service )。

問題是我正在考慮在下面的小半sudo代碼中運行類似於PHP的傳統順序代碼(我知道它不起作用,但僅舉例說明我將如何在PHP中解決它),但我知道我需要思考並行但不能完全了解我需要做什么讓控制器能夠將結果從AjaxOneAjaxTwo 請記住,兩種factory方法都不需要知道彼此的存在(不創建耦合,然后使其高度可重用)。

我如何使用Angular做我需要的東西?

app.controller('app', function( $http, $scope, AjaxOne, AjaxTwo ) {

    $scope.fields  = '';
    $scope.ajaxOne = AjaxOne;
    $scope.ajaxTwo = AjaxTwo;
    $scope.results = [];

    $scope.process = function () {
        AjaxOne.getResults($scope.fields);
        $scope.results = AjaxTwo.getResults(AjaxOne.results);
    };

});

謝謝。

您應該使用$ http服務獲得的承諾,它將提供這樣的東西

app.controller('app', function( $http, $scope, AjaxOne, AjaxTwo ) {

$scope.fields  = '';
$scope.results = [];

$scope.process = function () {
    AjaxOne.getResults($scope.fields).success(function(results){
        AjaxTwo.getResults(results).success(function(results2){
            $scope.results = results2;
        });
    });

};

});

有關更多信息,請查看此URL http://docs.angularjs.org/api/ng/service/ $ http

看起來你需要調整你的AjaxOne服務來接受一個回調,只有當AjaxOne完成它所做的任何事情時才會異步調用AjaxTwo

// Inside AjaxOne:

$scope.getResults = function(things, cb) {
  // do something with `things`. Let's assume you're using $http:
  $http({
    url: "http://example.appspot.com/rest/app",
    method: "POST",
    data: {
      "foo": "bar"
    }
  }).success(function(data, status, headers, config) {
    cb(data);
  });
};

// In your original example:

app.controller('app', function($http, $scope, AjaxOne, AjaxTwo) {

  $scope.fields = '';
  $scope.ajaxOne = AjaxOne;
  $scope.ajaxTwo = AjaxTwo;
  $scope.results = [];

  $scope.process = function() {
    AjaxOne.getResults($scope.fields, function(resultsFromAjaxOne) {
      $scope.results = AjaxTwo.getResults(resultsFromAjaxOne);
    });
  };

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM