AngularJS:使用异步数据初始化服务

时间:2013-04-29 19:25:07

标签: javascript angularjs asynchronous service angular-promise

我有一个AngularJS服务,我想用一些异步数据进行初始化。像这样:

myModule.service('MyService', function($http) {
    var myData = null;

    $http.get('data.json').success(function (data) {
        myData = data;
    });

    return {
        setData: function (data) {
            myData = data;
        },
        doStuff: function () {
            return myData.getSomeData();
        }
    };
});

显然这不起作用,因为如果在doStuff()返回之前某些东西试图调用myData,我将得到一个空指针异常。据我所知,在阅读其他一些问题herehere时,我有几个选择,但其中没有一个看起来很干净(也许我遗漏了一些东西):

使用“运行”设置服务

设置我的应用时,请执行以下操作:

myApp.run(function ($http, MyService) {
    $http.get('data.json').success(function (data) {
        MyService.setData(data);
    });
});

然后我的服务看起来像这样:

myModule.service('MyService', function() {
    var myData = null;
    return {
        setData: function (data) {
            myData = data;
        },
        doStuff: function () {
            return myData.getSomeData();
        }
    };
});

这种方法在某些时候有效,但是如果异步数据的执行时间比初始化所有内容要长,那么当我调用doStuff()

时会出现空指针异常

使用承诺对象

这可能会奏效。我称之为MyService的唯一缺点是我必须知道doStuff()返回一个promise,所有代码都必须由我们then与promise进行交互。在加载我的应用程序之前,我宁愿等到myData返回。

手动Bootstrap

angular.element(document).ready(function() {
    $.getJSON("data.json", function (data) {
       // can't initialize the data here because the service doesn't exist yet
       angular.bootstrap(document);
       // too late to initialize here because something may have already
       // tried to call doStuff() and would have got a null pointer exception
    });
});

全球Javascript Var 我可以将我的JSON直接发送到全局Javascript变量:

HTML:

<script type="text/javascript" src="data.js"></script>

data.js:

var dataForMyService = { 
// myData here
};

然后在初始化MyService

时可用
myModule.service('MyService', function() {
    var myData = dataForMyService;
    return {
        doStuff: function () {
            return myData.getSomeData();
        }
    };
});

这也可以,但是我有一个全局的javascript变量,闻起来很糟糕。

这些是我唯一的选择吗?这些选项中的一个比其他选项更好吗?我知道这是一个很长的问题,但我想表明我试图探索我的所有选择。非常感谢任何指导。

10 个答案:

答案 0 :(得分:324)

你看过$routeProvider.when('/path',{ resolve:{...}了吗?它可以使承诺更清洁:

在您的服务中公开承诺:

app.service('MyService', function($http) {
    var myData = null;

    var promise = $http.get('data.json').success(function (data) {
      myData = data;
    });

    return {
      promise:promise,
      setData: function (data) {
          myData = data;
      },
      doStuff: function () {
          return myData;//.getSomeData();
      }
    };
});

resolve添加到路线配置中:

app.config(function($routeProvider){
  $routeProvider
    .when('/',{controller:'MainCtrl',
    template:'<div>From MyService:<pre>{{data | json}}</pre></div>',
    resolve:{
      'MyServiceData':function(MyService){
        // MyServiceData will also be injectable in your controller, if you don't want this you could create a new promise with the $q service
        return MyService.promise;
      }
    }})
  }):

在解决所有依赖项之前,您的控制器不会被实例化:

app.controller('MainCtrl', function($scope,MyService) {
  console.log('Promise is now resolved: '+MyService.doStuff().data)
  $scope.data = MyService.doStuff();
});

我在plnkr上做了一个例子:http://plnkr.co/edit/GKg21XH0RwCMEQGUdZKH?p=preview

答案 1 :(得分:87)

基于Martin Atkins的解决方案,这是一个完整,简洁的纯角度解决方案:

(function() {
  var initInjector = angular.injector(['ng']);
  var $http = initInjector.get('$http');
  $http.get('/config.json').then(
    function (response) {
      angular.module('config', []).constant('CONFIG', response.data);

      angular.element(document).ready(function() {
          angular.bootstrap(document, ['myApp']);
        });
    }
  );
})();

此解决方案使用自执行匿名函数来获取$ http服务,请求配置,并在可用时将其注入名为CONFIG的常量中。

完成后,我们等到文档准备就绪,然后引导Angular应用程序。

这比Martin的解决方案略有改进,该解决方案推迟获取配置,直到文档准备好。据我所知,没有理由延迟$ http呼叫。

单元测试

注意:我发现当代码包含在app.js文件中进行单元测试时,此解决方案无效。原因是上面的代码在加载JS文件时立即运行。这意味着测试框架(在我的情况下是Jasmine)没有机会提供$http的模拟实现。

我的解决方案,我并不完全满意,是将此代码移到我们的index.html文件中,因此Grunt / Karma / Jasmine单元测试基础架构看不到它。

答案 2 :(得分:49)

我使用了与@XMLilley描述的方法类似的方法,但希望能够使用像$http这样的AngularJS服务来加载配置并在不使用低级API或jQuery的情况下进行进一步的初始化。 / p>

在路由上使用resolve也不是一个选项,因为我需要在启动应用程序时将值作为常量提供,即使在module.config()块中也是如此。

我创建了一个小的AngularJS应用程序来加载配置,将它们设置为实际应用程序上的常量并引导它。

// define the module of your app
angular.module('MyApp', []);

// define the module of the bootstrap app
var bootstrapModule = angular.module('bootstrapModule', []);

// the bootstrapper service loads the config and bootstraps the specified app
bootstrapModule.factory('bootstrapper', function ($http, $log, $q) {
  return {
    bootstrap: function (appName) {
      var deferred = $q.defer();

      $http.get('/some/url')
        .success(function (config) {
          // set all returned values as constants on the app...
          var myApp = angular.module(appName);
          angular.forEach(config, function(value, key){
            myApp.constant(key, value);
          });
          // ...and bootstrap the actual app.
          angular.bootstrap(document, [appName]);
          deferred.resolve();
        })
        .error(function () {
          $log.warn('Could not initialize application, configuration could not be loaded.');
          deferred.reject();
        });

      return deferred.promise;
    }
  };
});

// create a div which is used as the root of the bootstrap app
var appContainer = document.createElement('div');

// in run() function you can now use the bootstrapper service and shutdown the bootstrapping app after initialization of your actual app
bootstrapModule.run(function (bootstrapper) {

  bootstrapper.bootstrap('MyApp').then(function () {
    // removing the container will destroy the bootstrap app
    appContainer.remove();
  });

});

// make sure the DOM is fully loaded before bootstrapping.
angular.element(document).ready(function() {
  angular.bootstrap(appContainer, ['bootstrapModule']);
});

在此处查看该广告(使用$timeout代替$http):http://plnkr.co/edit/FYznxP3xe8dxzwxs37hi?p=preview

<强>更新

我建议使用Martin Atkins和JBCP下面描述的方法。

更新2

因为我需要在多个项目中使用它,所以我刚刚发布了一个用于处理此问题的bower模块:https://github.com/philippd/angular-deferred-bootstrap

从后端加载数据并在AngularJS模块上设置一个名为APP_CONFIG的常量的示例:

deferredBootstrapper.bootstrap({
  element: document.body,
  module: 'MyApp',
  resolve: {
    APP_CONFIG: function ($http) {
      return $http.get('/api/demo-config');
    }
  }
});

答案 3 :(得分:42)

“手动引导程序”案例可以通过在引导程序之前手动创建注入器来访问Angular服务。此初始注入器将独立存在(不附加到任何元素),并且仅包括已加载的模块的子集。如果您只需要核心Angular服务,只需加载ng即可,如下所示:

angular.element(document).ready(
    function() {
        var initInjector = angular.injector(['ng']);
        var $http = initInjector.get('$http');
        $http.get('/config.json').then(
            function (response) {
               var config = response.data;
               // Add additional services/constants/variables to your app,
               // and then finally bootstrap it:
               angular.bootstrap(document, ['myApp']);
            }
        );
    }
);

例如,您可以使用module.constant机制为您的应用提供数据:

myApp.constant('myAppConfig', data);

myAppConfig现在可以像任何其他服务一样注入,特别是在配置阶段可用:

myApp.config(
    function (myAppConfig, someService) {
        someService.config(myAppConfig.someServiceConfig);
    }
);

或者,对于较小的应用程序,您可以直接将全局配置注入到您的服务中,但代价是在整个应用程序中传播有关配置格式的知识。

当然,由于此处的异步操作将阻止应用程序的引导程序,从而阻止模板的编译/链接,因此使用ng-cloak指令防止未解析的模板在出现期间显示是明智的。工作。您还可以在DOM中提供某种加载指示,方法是提供一些只在AngularJS初始化之前显示的HTML:

<div ng-if="initialLoad">
    <!-- initialLoad never gets set, so this div vanishes as soon as Angular is done compiling -->
    <p>Loading the app.....</p>
</div>
<div ng-cloak>
    <!-- ng-cloak attribute is removed once the app is done bootstrapping -->
    <p>Done loading the app!</p>
</div>

我在Plunker上创建了此方法的a complete, working example,从静态JSON文件加载配置作为示例。

答案 4 :(得分:14)

我遇到了同样的问题:我喜欢resolve对象,但这只适用于ng-view的内容。如果您在ng-view之外存在控制器(用于顶层导航,并且在路由开始发生之前需要使用数据进行初始化),该怎么办?我们如何避免在服务器端乱搞只是为了使其工作?

使用手动引导程序和角度常量。一个简单的XHR可以获取您的数据,并在其回调中引导角度,这将处理您的异步问题。在下面的示例中,您甚至不需要创建全局变量。返回的数据仅作为可注入的角度范围存在,并且除非您注入它,否则甚至不存在于控制器,服务等内部。 (就像你将resolve对象的输出注入控制器以获取路由视图一样。)如果您希望此后作为服务与该数据进行交互,则可以创建服务,注入数据,并且没有人将永远是明智的。

示例:

//First, we have to create the angular module, because all the other JS files are going to load while we're getting data and bootstrapping, and they need to be able to attach to it.
var MyApp = angular.module('MyApp', ['dependency1', 'dependency2']);

// Use angular's version of document.ready() just to make extra-sure DOM is fully 
// loaded before you bootstrap. This is probably optional, given that the async 
// data call will probably take significantly longer than DOM load. YMMV.
// Has the added virtue of keeping your XHR junk out of global scope. 
angular.element(document).ready(function() {

    //first, we create the callback that will fire after the data is down
    function xhrCallback() {
        var myData = this.responseText; // the XHR output

        // here's where we attach a constant containing the API data to our app 
        // module. Don't forget to parse JSON, which `$http` normally does for you.
        MyApp.constant('NavData', JSON.parse(myData));

        // now, perform any other final configuration of your angular module.
        MyApp.config(['$routeProvider', function ($routeProvider) {
            $routeProvider
              .when('/someroute', {configs})
              .otherwise({redirectTo: '/someroute'});
          }]);

        // And last, bootstrap the app. Be sure to remove `ng-app` from your index.html.
        angular.bootstrap(document, ['NYSP']);
    };

    //here, the basic mechanics of the XHR, which you can customize.
    var oReq = new XMLHttpRequest();
    oReq.onload = xhrCallback;
    oReq.open("get", "/api/overview", true); // your specific API URL
    oReq.send();
})

现在,您的NavData常量存在。继续将其注入控制器或服务中:

angular.module('MyApp')
    .controller('NavCtrl', ['NavData', function (NavData) {
        $scope.localObject = NavData; //now it's addressable in your templates 
}]);

当然,使用一个简单的XHR对象会剥离$http或JQuery会为你处理的一些细节,但是这个例子没有特殊的依赖关系,至少对于一个简单的{{1 }}。如果您想为请求提供更多功能,请加载外部库以帮助您。但我不认为在这种情况下可以访问angular get或其他工具。

(SO related post

答案 5 :(得分:8)

你可以做的是在.config中为app创建路由的解析对象,并在函数传递$ q(promise对象)和你所依赖的服务的名称,并解决承诺在服务的$ http回调函数中如下:

ROUTE CONFIG

app.config(function($routeProvider){
    $routeProvider
     .when('/',{
          templateUrl: 'home.html',
          controller: 'homeCtrl',
          resolve:function($q,MyService) {
                //create the defer variable and pass it to our service
                var defer = $q.defer();
                MyService.fetchData(defer);
                //this will only return when the promise
                //has been resolved. MyService is going to
                //do that for us
                return defer.promise;
          }
      })
}

在调用defer.resolve()之前,Angular不会渲染模板或使控制器可用。我们可以在我们的服务中做到这一点:

SERVICE

app.service('MyService',function($http){
       var MyService = {};
       //our service accepts a promise object which 
       //it will resolve on behalf of the calling function
       MyService.fetchData = function(q) {
             $http({method:'GET',url:'data.php'}).success(function(data){
                 MyService.data = data;
                 //when the following is called it will
                 //release the calling function. in this
                 //case it's the resolve function in our
                 //route config
                 q.resolve();
             }
       }

       return MyService;
});

既然MyService已经为其数据属性分配了数据,并且路径解析对象中的promise已经解析,我们的路由控制器就会生效,我们可以将服务中的数据分配给控制器对象。

CONTROLLER

  app.controller('homeCtrl',function($scope,MyService){
       $scope.servicedata = MyService.data;
  });

现在我们在控制器范围内的所有绑定都能够使用源自MyService的数据。

答案 6 :(得分:5)

所以我找到了解决方案。我创建了一个angularJS服务,我们称之为MyDataRepository,我为它创建了一个模块。然后我从服务器端控制器提供这个javascript文件:

<强> HTML:

<script src="path/myData.js"></script>

服务器侧

@RequestMapping(value="path/myData.js", method=RequestMethod.GET)
public ResponseEntity<String> getMyDataRepositoryJS()
{
    // Populate data that I need into a Map
    Map<String, String> myData = new HashMap<String,String>();
    ...
    // Use Jackson to convert it to JSON
    ObjectMapper mapper = new ObjectMapper();
    String myDataStr = mapper.writeValueAsString(myData);

    // Then create a String that is my javascript file
    String myJS = "'use strict';" +
    "(function() {" +
    "var myDataModule = angular.module('myApp.myData', []);" +
    "myDataModule.service('MyDataRepository', function() {" +
        "var myData = "+myDataStr+";" +
        "return {" +
            "getData: function () {" +
                "return myData;" +
            "}" +
        "}" +
    "});" +
    "})();"

    // Now send it to the client:
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "text/javascript");
    return new ResponseEntity<String>(myJS , responseHeaders, HttpStatus.OK);
}

然后我可以在需要的地方注入MyDataRepository:

someOtherModule.service('MyOtherService', function(MyDataRepository) {
    var myData = MyDataRepository.getData();
    // Do what you have to do...
}

这对我来说很有用,但如果有人有任何反馈,我愿意接受任何反馈。 }

答案 7 :(得分:2)

此外,在执行实际控制器之前,您可以使用以下技术全局配置服务:https://stackoverflow.com/a/27050497/1056679。只需全局解析您的数据,然后将其传递到run块中的服务。

答案 8 :(得分:1)

您可以使用JSONP异步加载服务数据。 JSONP请求将在初始页面加载期间生成,结果将在应用程序启动之前可用。这样,您就不必通过冗余解决方案来扩展路由。

你的HTML看起来像这样:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>

function MyService {
  this.getData = function(){
    return   MyService.data;
  }
}
MyService.setData = function(data) {
  MyService.data = data;
}

angular.module('main')
.service('MyService', MyService)

</script>
<script src="/some_data.php?jsonp=MyService.setData"></script>

答案 9 :(得分:-1)

获取任何初始化的最简单方法是使用ng-init目录。

只需将ng-init div范围放在要获取init数据的位置

<强>的index.html

<div class="frame" ng-init="init()">
    <div class="bit-1">
      <div class="field p-r">
        <label ng-show="regi_step2.address" class="show-hide c-t-1 ng-hide" style="">Country</label>
        <select class="form-control w-100" ng-model="country" name="country" id="country" ng-options="item.name for item in countries" ng-change="stateChanged()" >
        </select>
        <textarea class="form-control w-100" ng-model="regi_step2.address" placeholder="Address" name="address" id="address" ng-required="true" style=""></textarea>
      </div>
    </div>
  </div>

<强> index.js

$scope.init=function(){
    $http({method:'GET',url:'/countries/countries.json'}).success(function(data){
      alert();
           $scope.countries = data;
    });
  };
  

注意:如果您的代码不多于一个地方,则可以使用此方法。