我是AngularJs的新手。我正在调用http
调用来获取名称列表,我想在应用程序加载后立即调用它。因此,我编写了逻辑来获取angularjs上run
函数中的名称列表。我使用自定义service
来获取名称并在run
方法中调用函数。
服务方法中的代码如下:
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 :(得分: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;
);
}]);