我是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方法已經執行。
請讓我知道我要去哪裏錯了。
由於ajax請求是一個異步調用,所以run函數不會等待請求的完成。 **順便說一句,有什麼問題?** – Vivek
我想在我的run方法中使用設置爲rootScope的屬性,但由於這是異步的,我沒有在'run'函數中獲取值。 – zilcuanu
我收到錯誤在我的'run'功能 類型錯誤:fetchData.fetchNames不是一個函數 運行函數中的代碼是 fetchData.fetchNames(); – zilcuanu