Injecting a resolved promise into service

后端 未结 2 1494
囚心锁ツ
囚心锁ツ 2021-02-08 01:29

I need to get some information (a schema) from the server before I set up a bunch of services that depend on that information.

My server provides a schema that defines v

相关标签:
2条回答
  • 2021-02-08 01:35

    You get a promise because your service function immediately evaluates its body when you call it (as functions do). Normally, a service should return an object so that the consumer (another service, controller, whatever) may then call the functions on that object when it needs to.

    services.factory('schema', function($q, $http) {
    return {
      get: function() {
        var deferred = $q.defer();
        $http.get('schema/').then(function(response) {
          schema = // some function of response.data
          deferred.resolve(schema);
        }, function() {
          deferred.reject('There was a problem fetching the schema');
        });
        return deferred.promise;
      }
    }
    

    });

    0 讨论(0)
  • 2021-02-08 01:48

    What you want is deferred bootstrap. There is already a plugin written for this purpose - https://github.com/philippd/angular-deferred-bootstrap.

    I create an example at plunkr - http://plnkr.co/edit/VfISHNULXRLe52NeAsn1?p=preview

    *You must replace existing ng-app with deferred bootstrap

    Code Snippet -

    angular.element(document).ready(function() {
        deferredBootstrapper.bootstrap({
            element: document.body,
            module: 'plunker',
            resolve: {
                schema: ['$http',
                    function($http) {
                        return $http.get('schema.json');
                    }
                ]
            }
        });
    });
    

    Then, you can use schema anyway in controller, services or factory just like route resolve.

    Sample Code for Factory

    app.factory('SomeService', function(schema){
        return {
            getTitle: function() {
                return schema.title;
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题