Amb*_*ite 6 javascript angularjs angular-ui-router
我有一个UI路由器定义类似这样(为简单起见修剪):
$stateProvider
.state('someState', {
resolve: {
model: ['modelService', 'info', function (modelService, info) {
return modelService.get(info.id).$promise;
}]
},
controller: 'SomeController'
});
Run Code Online (Sandbox Code Playgroud)
此someState状态正在使用依赖于该model解析的工厂/服务.它的定义是这样的,AngularJS会抛出一个未知的提供者:modelProvider < - model < - someService错误:
angular
.module('someModule')
.factory('someService', someService);
someService.$inject = ['model'];
function someService(model) { ... }
Run Code Online (Sandbox Code Playgroud)
但是,model在此状态的控制器内使用相同的解决方案可以正常工作:
SomeController.$inject = ['model'];
function SomeController(model) { ... }
Run Code Online (Sandbox Code Playgroud)
所以我理解UI路由器正在推迟SomeController解决方案的DI ,这允许AngularJS不会抛出错误.但是,当把这个决心作为一个依赖时,怎么会发生同样的延迟someService呢?解析只能在控制器上工作吗?如果是这种情况,我如何在工厂/服务中使用解决方案?
Ed *_*ffe 14
Do resolves only work on controllers?
Yes, resolves only work on controllers.
And if that is the case, how can I use a resolve inside a factory/service?
Remember that factories and services return singleton objects, i.e. the first time a factory is injected into a controller, it runs any instantiation code you provide and creates an object, and then any subsequent times that factory is instantiated, that same object is returned.
In other words:
angular.module('someModule')
.factory( 'SomeFactory' , function () {
// this code only runs once
object = {}
object.now = Date.now();
return object
);
Run Code Online (Sandbox Code Playgroud)
SomeFactory.now will be the current time the first time the factory is injected into a controller, but it not update on subsequent usage.
As such, the concept of resolve for a factory doesn't really make sense. If you want to have a service that does something dynamically (which is obviously very common), you need to put the logic inside functions on the singleton.
For example, in the code sample you gave, your factory depended on a model. One approach would be to inject the model into the controller using the resolve method you've already got set up, then expose a method on the singleton that accepts a model and does what you need to do, like so:
angular.module('someModule')
.factory( 'SomeFactory', function () {
return {
doSomethingWithModel: function (model) {
$http.post('wherever', model);
}
});
.controller('SomeController', function (SomeFactory, model) {
SomeFactory.doSomethingWithModel(model);
});
Run Code Online (Sandbox Code Playgroud)
Alternatively, if you don't need the resolved value in the controller at all, don't put it directly in a resolve, instead put the resolve logic into a method on the service's singleton and call that method inside the resolve, passing the result to the controller.
抽象对话很难更详细,所以如果你需要进一步的指针,那么提供一个特定的用例.
| 归档时间: |
|
| 查看次数: |
8245 次 |
| 最近记录: |