2014-11-02 36 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