The provider() function allows us to create a configurable service where we can set input per application for the service created using the provider (). For example, if we need to set API key to access a service on the application level, we can set that in the module config and pass input to the provider using the $provide service. All the others ways to create services internally use the $provide service.
Creating a service using $provide service in module.config
Let us start by creating a very simple service using the provider() function.
app.config(function ($provide) { $provide.provider('globalsetting', function () { this.$get = function () { var appname = "Lawyer App"; return { appName: appname }; } }) });
Let’s explore what is going on in the above snippet. To create a service using provider, we need to use the $provide service. The provider function of the $provide service takes two parameters: the name of the service and the function. A provider function must have a $get function. To create a simple service using the provider(), we need to perform following five steps:
- Inject the $provide service in the app config method
- Create a provider using the provider() function
- Pass two parameters to the provider() function: the name of the service and a function
- The provider function must contain a $get function
- Return an object literal from the $get function
We can use the globalsetting service created using the provider by injecting it in a controller as shown in the listing below:
Leave a Reply