2015-11-26 92 views
0

我是AngularJs的新手。我打電話給一個http獲取調用來獲取一個名稱列表,我希望它一應用程序加載。因此,我寫了邏輯來獲取angularjs上的run函數中的名稱列表。我正在使用自定義service來獲取名稱並調用run方法中的函數。在angularjs中設置http調用後的作用域元素

在服務方法的代碼如下:

angular.module('myApp') 
    .service('fetchData', function ($http, $rootScope) { 
    // AngularJS will instantiate a singleton by calling "new" on this function 
    this.fetchNames = function() { 
     $http.get('http://hostname:port/names').success(function (person) { 
      $rootScope.names = person.names; 
     }); 
    } 

在我app.js,我有如下代碼:

angular.module('myApp', ['ngRoute']) 
.config(function ($routeProvider, $locationProvider) { 
    $routeProvider 
     .otherwise({ 
     redirectTo: '/' 
     }); 

    $locationProvider.html5Mode(true); 
}) 

.run (function($rootScope, fetchData){ 
    //first make an ajax call and fetch all the applicatons for the given BU 
    fetchData.fetchNames(); 
}); 

但受fetchNames得到名稱形成http調用,run方法已經執行。

請讓我知道我要去哪裏錯了。

+0

由於ajax請求是一個異步調用,所以run函數不會等待請求的完成。 **順便說一句,有什麼問題?** – Vivek

+0

我想在我的run方法中使用設置爲rootScope的屬性,但由於這是異步的,我沒有在'run'函數中獲取值。 – zilcuanu

+0

我收到錯誤在我的'run'功能 類型錯誤:fetchData.fetchNames不是一個函數 運行函數中的代碼是 fetchData.fetchNames(); – zilcuanu

回答

0

在您的服務中,您可以返回承諾,然後在您的運行功能中處理成功。

angular.module('myApp') 
    .service('fetchData', function ($http, $rootScope) { 
    // AngularJS will instantiate a singleton by calling "new" on this function 
    this.fetchNames = function() { 
     return $http.get('http://hostname:port/names'); 
    } 

現在,您可以在運行中處理成功事件。

.run (['$rootScope', 'fetchData', function($rootScope, fetchData){ 
    //first make an ajax call and fetch all the applicatons for the given BU 
    fetchData.fetchNames().success(function (person) { 
      $rootScope.names = person.names; 
    ); 
}]); 
+0

明白了。這是異步調用的方式。但是,由於我使用自定義指令來顯示名稱,並且自定義指令具有隔離範圍,因此如何使名稱在指令中可用。我的意思是,在那個時候,這些名字被設置在'run'函數中,該指令將被調用。什麼是使命令可用的最佳方式。 – zilcuanu

+0

@Pradeep您可以使用雙向綁定並將名稱傳遞給指令。只要名稱通過ajax調用更新,它們就會反映到您綁定名稱的指令變量中。 – Vivek

+0

可以請你解釋一下plnkr上的例子。如果我可以按照您所說的方式實施,那將非常酷。 – zilcuanu

相關問題