问题
I want to move some of the repetitive logic out in a reusable service, which must be available in a config phase. And possibly have access to $xxxProvider
dependency injections too. Is such thing possible? Can one do this with factory/provider/service/constant ?
To be specific, when I define my routes with ui-router
, I noticed that routes for CRUD are all the same, except for the names of the resources. So i'd like to move this logic of configuring a CRUD route somewhere to make route definitions more DRY.
回答1:
For accessing your service provider in the config block, this should work just fine:
app.service('myService', function (/* dependencies */) {
// service stuff..
return this;
});
app.config(function ($provide) {
$provide.decorator('myService', function ($delegate) {
// $delegate refers to 'myService'.
// You can modify its behaviour and what not in here.
return $delegate;
});
});
I'm not crystal clear on what you are looking for, but this 'just works'.
Do note, that the service registration needs to come before the config
block if they reside in the same file. A way to overcome this, would be to extract your service into a separate module and inject it as a dependency to your main module. Something like this:
var serviceModule = angular.module('serviceModule', []);
serviceModule.service('myService', function () {});
var mainModule = angular.module('main', ['serviceModule']);
mainModule.config(function ($provide) {
$provide.decorator('myService', function ($delegate) {});
});
JsBin: http://jsbin.com/pasiquju/2/edit
Edit
I've now put together a rough example of how you could do the following:
- Register your own custom provider constructor, that returns an object.
- Inject another
provider
into your own provider, passing through functionality from one constructor to another. - Register a secondary service, that gets injected into the provider constructor.
- Pass some more functionality from the
app.config
block to your provider constructor. - Inject the instance returned by the constructor into a controller.
- Output the end data from the instance returned by the constructor, with args.
This should cover the needs specified:
- Prone to DI, from
providers
. - Prone to DI, from services.
- Available during config phase.
JsBin: http://jsbin.com/jenumobi/2/edit
And here's the documentation for the provider
shorthand methods, and how they differ. As you can clearly see, the provider
core function is the one with the most options available to it - but also the hardest to work with, for obvious reasons.
I hope that will do enough for you, and give you some sort of idea on how to create your own $stateProvider
extension! I've done my best to document the code in the JsBin to make it easier to understand just how it all ties together.
来源:https://stackoverflow.com/questions/24954712/angular-service-available-at-configuration-phase