AngularJS : Initialize service with asynchronous data

后端 未结 10 1759
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:09

I have an AngularJS service that I want to initialize with some asynchronous data. Something like this:

myModule.service(\'MyService\', function($http) {
            


        
10条回答
  •  时光说笑
    2020-11-22 03:24

    Have you had a look at $routeProvider.when('/path',{ resolve:{...}? It can make the promise approach a bit cleaner:

    Expose a promise in your service:

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

    Add resolve to your route config:

    app.config(function($routeProvider){
      $routeProvider
        .when('/',{controller:'MainCtrl',
        template:'
    From MyService:
    {{data | json}}
    ', 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; } }}) }):

    Your controller won't get instantiated before all dependencies are resolved:

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

    I've made an example at plnkr: http://plnkr.co/edit/GKg21XH0RwCMEQGUdZKH?p=preview

提交回复
热议问题