如何从服务中检索 ajax 响应值?

how to retrieve ajax response value from service?

我在控制器中使用了 2 个服务 第一项服务是获取 AjaxResponse,其中提到了获取响应的逻辑 第二个服务调用第一个服务发出 Http 请求并获取结果,然后 return 将其返回给控制器

Ctrl依赖注入firstService,secondService

this.getService = secondService.getData(param);

第一个服务--> firstService

this.httpResponse(param){
   var re = $http.get(param);
  return re.then(success,fail);
}
function success(data){
   return data;
}
function fail(data){
   console.log(data);
}

第二个服务(第一个服务的依赖注入)

function secondService(firstService){
    this.getData = function(param){
       return firstService.httpResponse(param);
    };
}

this.getService 未定义,所有调用都正常进行。

甚至尝试了以下代码:

secondService.getData(param).then(function(data){console.log(data);});

这也无济于事。

在这种情况下,您应该链接 promise。

首先,您定义服务。它应该包含两个不同的功能。例如,我做了一个 GET 和一个 POST.

angular.module("myApp",[]).factory("SharedServices", function($http) {
    return {
        getItem: function() {
            return $http.get('path/to/api');
        },
        postItem: function(payload) {
            return $http.post('path/to/api', payload);
        }
    };
});

然后,在您的控制器中引用该服务。 getItem() 将 return 一个承诺,您可以在其中使用 .then 在成功回调中调用您的第二个服务。

angular.module("myApp",[]).controller("MainCtrl", function($scope, SharedServices) {
    SharedServices.getItem().then(function(response) {
        //success, got something
        //call the second part
        var payload = { myPayload: response.data.someItem };
        SharedServices.postItem(payload).then(function(response) {
            //success
        }, function(response) {
            //an error has occurred to the second call--POST
        });
    }, function(response) {
        //an error occurred to the first call--GET
    });
});

使用回调获取 result.It 类似于 deferred(promise)