Earlier in this chapter, we discussed using the module provider
method to create a service with configuration methods that consumers of your service can invoke in a module's config
method.
By using the provider
method to define the example logging service, consumers can now configure the logging service inside a module's config
method in a rather straightforward way:
angular.module('MyApp', ['logging']).config(function(loggingProvider){ // init the logging service loggingProvider.init(); // set the log level loggingProvider.setLogLevel(log4javascript.Level.ALL); // create and add an appender to the logger var appender = new log4javascript.PopUpAppender(); loggingProvider.setAppender(appender); });
In the preceding code, we initialize our service, set the logging level, and set the logging appender to be used when messages are logged by the service.
However, you don't always have to use the provider
method to allow your services to be configured. You can use both the service
and factory
methods to define your service and provide configuration methods that can be called in a module's run
method, which executes after your application has been bootstrapped. You just need to ensure your service follows the design practices we discussed earlier and doesn't try to call any external services as it is instantiated.
No matter how you create your services, by providing functionality to configure the services you create, you make your services more flexible, easier to use, and reduce the complexity required to include them in an application.
3.21.43.26