注入解决承诺投入使用 [英] Injecting a resolved promise into service
问题描述
我需要从服务器获取一些信息(架构)之前,我成立了一堆依赖于信息的服务。
I need to get some information (a schema) from the server before I set up a bunch of services that depend on that information.
我的服务器提供了定义模型的各种属性的模式。在我的角度code,我应该得到这个模式的服务:
My server provides a schema that defines various properties of a model. In my angular code, I have a service that gets this schema:
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;
});
我想注入架构对象,而不是承诺,将依赖于模式的其他服务。 $ routeProvider让我们的控制器做到这一点:
I would like to inject the schema object, and not the promise, into other services that depend on the schema. $routeProvider lets us do this for controllers:
app.config(function($routeProvider) {
$routeProvider.
when('/', {
controller: 'SomeCtrl',
resolve: {
schema: 'schema'
},
...
});
});
这让我定义SomeCtrl是这样的:
and this allows me to define SomeCtrl like this:
controllers.controller('SomeCtrl', function($scope, schema) {
// schema is an object
...
});
但对于服务,我要做的:
But for services, I have to do:
services.factory('SomeService', function(schema) {
// schema is a promise
schema.then(function(schema) {
...
});
});
有没有什么办法可以做到这一点?
Is there any way I can do this?
推荐答案
你想要的是递延引导。目前已经为此写了一个插件 - https://github.com/philippd/angular-deferred -bootstrap 。
What you want is deferred bootstrap. There is already a plugin written for this purpose - https://github.com/philippd/angular-deferred-bootstrap.
我在创建一个plunkr例子 - http://plnkr.co/edit/ VfISHNULXRLe52NeAsn1?p = preVIEW
I create an example at plunkr - http://plnkr.co/edit/VfISHNULXRLe52NeAsn1?p=preview
*您必须替换现有的NG-应用与递延引导
*You must replace existing ng-app with deferred bootstrap
code片段 -
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.
样code工厂
app.factory('SomeService', function(schema){
return {
getTitle: function() {
return schema.title;
}
}
});
这篇关于注入解决承诺投入使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!