在angularjs中的http调用之后设置scope元素



我是AngularJs的新手。我正在调用http get调用来获取名称列表,我希望在应用程序加载后立即获取。因此,我编写了在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方法已经被执行了。

请告诉我哪里出了问题。

在您的服务中,您可以返回promise,然后在运行函数中处理成功。

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;
    );
}]);

最新更新