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

时间:2015-11-26 09:43:26

标签: angularjs angularjs-scope angularjs-service

我是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方法已经执行了。

请让我知道我哪里出错。

1 个答案:

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