2014-11-02 62 views
0

我想在第一个控制器中获取http请求结果。 http请求由另一个控制器触发。我有的问题是我不知道如何检测请求是否在我的第一个控制器中完成。我有一些像如何在我的例子中获取http请求数据?

第一控制器:

//I am not sure how to get the customer result if 
//http requests are trigger by another controllers here. 

customerFactory.getCustomerResult???? 

第二个控制器:

//trigger the http request.. 
var id = 1; 
$scope.clickme = function() { 
    var obj = customerFactory.callApi(id) 
} 

我厂

customerFactory.callApi = function(id) { 
    return getCustomer(id) 
     .then(function(customer) { 
      return customer;  

     }) 
} 

var getCustomer = function(id) { 
    return $http.get('/api/project1/getCustomer' + id); 
} 

return customerFactory; 

HTML

<div ng-controller="firstCtrl"> 
    //codes... 
</div> 

//other codes.. 
//other codes.. 

<div ng-controller="secondCtrl"> 
    //codes... 
</div> 

第一个和第二个控制器不相关。他们彼此远离。如何让firstCtrl检测到http请求已完成并获取客户数据?非常感谢!

回答

1

您可以使用工厂或单身服务来负责提出请求并存储数据。服务和工厂都是单例,所以单实例持续执行应用程序,并且可以通过注入工厂或服务从控制器引用数据和函数(两者都是在配置之前用更简洁的语法定义提供程序的方法不需要通过提供商使用服务/工厂)。

angular.module("exampleApp", []).service('ExampleService', ["$http", "$q" ,function ($http, $q) { 
    var service = { 
     returnedData: [], 
     dataLoaded:{}, 
     getData = function(forceRefresh) 
     { 
      var deferred = $q.defer(); 

      if(!service.dataLoaded.genericData || forceRefresh) 
      { 
       $http.get("php/getSomeData.php").success(function(data){ 
        angular.copy(data, service.returnedData) 
        service.dataLoaded.genericData = true; 
        deferred.resolve(service.returnedData); 
       }); 
      } 
      else 
      { 
       deferred.resolve(service.returnedData); 
      } 

      return deferred.promise; 
     }, 
     addSomeData:function(someDataToAdd) 
     { 
      $http.post("php/addSomeData.php", someDataToAdd).success(function(data){ 
       service.getData(true); 
      }); 
     } 
    }; 
    return service; 
}]).controller("ExampleCtrl", ["$scope", "ExampleService", function($scope, ExampleService){ 
    $scope.ExampleService = ExampleService; 
}]).controller("ExampleCtrl2", ["$scope", "ExampleService", function($scope, ExampleService){ 
    ExampleService.getData(); 
    $scope.ExampleService = ExampleService; 
}]); 
+0

谢谢shaunhusain,你的例子显示了一个控制器调用的是ExampleService.getData的调用,但它如何将返回数据传递给另一个控制器? +1 – BonJon 2014-11-02 02:45:20

+0

刚刚编辑显示第二个控制器,它与第一个控制器是一样的,只是我正在做的和你在做什么之间的真正区别是我还将数据存储在服务中(工厂也很好)所以这种方式可以从两个地方引用。有一些选择,但通常这是我遇到的最好的方式。也是公平的,我从这个其他答案我的代码,但我有这个问题很多次,并提到人们这个其他帖子http://stackoverflow.com/questions/17667455/angular-http-vs-service-vs- ngresource – shaunhusain 2014-11-02 02:48:40

+0

感谢您的帮助!我的问题是我需要在ExampleCtrl中触发http请求,但让ExampleCtrl2获取数据。如果我理解正确,ExampleCtrl2需要调用getData来获取数据。我只想要ExampleCtrl来调用getData方法。 – BonJon 2014-11-02 03:00:14