简体   繁体   English

使用AngularJS进行多服务http调用

[英]Multiple service http calls using AngularJS

In my controller I am calling a service with the following code: 在我的控制器中,我使用以下代码调用服务:

Service.updateData(data).then(function (result) {
  console.log(result);
});

In my service I am using $q to get multiple HTTP requests. 在我的服务中,我使用$ q来获取多个HTTP请求。

$rootScope.http_1 = $http.get();
$rootScope.http_2 = $http.get();

$q.all([$rootScope.http_1, $rootScope.http_2]).then(function(result) {
    console.log(result[0], result[1]);
    return result[0], result[1];
});

The code actually works as the http requests are successfully made. 该代码实际上是在成功发出http请求时起作用的。 However, I get an error in the controller which says: TypeError: Cannot read property 'then' of undefined. 但是,我在控制器中收到一条错误消息:TypeError:无法读取未定义的属性“ then”。 I believe this is due the service not returning the promise in the correct way. 我相信这是由于服务未以正确的方式退还承诺。 Any ideas on how to resolve this would be much appreciated? 任何有关如何解决此问题的想法将不胜感激?

It looks like you are not returning the promise in updateData Try this: 看来您没有在updateData返回诺言请尝试以下操作:

updateData = function(data) {
    $rootScope.http_1 = $http.get();
    $rootScope.http_2 = $http.get();

    return $q.all([$rootScope.http_1, $rootScope.http_2]);
}
  1. You didn't return the promise, so there is nothing to call .then() on in your controller 您没有返回承诺,因此您无需在控制器中调用.then()
  2. You are returning inside the .then() function inside your service.updateData() , which doesn't do very much for you. 您将在service.updateData()内部的.then()函数内部返回,这对您没有多大帮助。

If you want to control it all inside the service and return a specific format, try this: 如果要在服务中全部控制并返回特定格式,请尝试以下操作:

updateData = function(data) {
    $rootScope.http_1 = $http.get();
    $rootScope.http_2 = $http.get();
    var defer = $q.defer();
    $q.all([$rootScope.http_1, $rootScope.http_2]).then(function(result){
       // process here to get the data how you want it, say in some new var foo
       var foo = "some processed data based on result";
       defer.resolve(foo);
    });
    return defer.promise;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM