我在一个服务中有两个ajax调用;第一个,AjaxOne
从fields
(用户输入)获取我想要的数据,然后我想通过将数据传递给另一个 ajax 调用 AjaxTwo 来更改数据
以获得我需要的结果。两个 ajax 调用都是完全不同的服务,可以通过多个 Controller 进行交互,因此我将其放置在它们自己独特的 Angular factory
方法中(可以是 service
)。
问题是我正在考虑在下面的半 sudo 代码中运行类似于 PHP 的传统顺序代码(我知道它不会工作,但只是举例说明我如何在 PHP 中解决它),但我知道我需要并行思考,但无法完全理解我需要做什么才能使 Controller 能够将结果从 AjaxOne
传递到 AjaxTwo
。请记住,这两种工厂
方法不需要知道彼此的存在(以不产生耦合并使其高度可重用)。
我将如何使用 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);
};
});
谢谢。
最佳答案
似乎您需要调整 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);
});
};
});
关于javascript - 通过 AngularJS 中的 Controller 将结果从一个工厂/服务 ajax 方法传递到另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21962591/