将已解决的承诺注入服务中

use*_*201 12 javascript angularjs angular-promise

在设置依赖于该信息的一堆服务之前,我需要从服务器获取一些信息(模式).

我的服务器提供了一个定义模型各种属性的模式.在我的角度代码中,我有一个获取此架构的服务:

services.factory('schema', function($q, $http) {
    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;
});
Run Code Online (Sandbox Code Playgroud)

我想将架构对象而不是promise作为注入依赖于架构的其他服务.$ routeProvider允许我们为控制器执行此操作:

app.config(function($routeProvider) {
    $routeProvider.
        when('/', {
            controller: 'SomeCtrl',
            resolve: {
                schema: 'schema'
            },
            ...
        });
});
Run Code Online (Sandbox Code Playgroud)

这允许我像这样定义SomeCtrl:

controllers.controller('SomeCtrl', function($scope, schema) {
    // schema is an object
    ...
});
Run Code Online (Sandbox Code Playgroud)

但对于服务,我必须这样做:

services.factory('SomeService', function(schema) {
    // schema is a promise
    schema.then(function(schema) {
        ...
    });
});
Run Code Online (Sandbox Code Playgroud)

有什么方法可以做到这一点吗?

hut*_*ung 5

你想要的是延迟bootstrap.已经有一个为此目的编写的插件 - https://github.com/philippd/angular-deferred-bootstrap.

我在plunkr上创建了一个例子 - http://plnkr.co/edit/VfISHNULXRLe52NeAsn1?p=preview

*您必须使用延迟引导程序替换现有的ng-app

代码片段 -

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

然后,您可以在控制器,服务或工厂中使用架构,就像路由解析一样.

工厂示例代码

app.factory('SomeService', function(schema){
    return {
        getTitle: function() {
            return schema.title;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


sup*_*her -1

您得到了一个承诺,因为您的服务函数在您调用它时立即评估其主体(就像函数一样)。通常,服务应该返回一个对象,以便消费者(另一个服务、控制器等)可以在需要时调用该对象上的函数。

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

});