What is a Provider () in AngularJS?

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:

  1. Inject the $provide service in the app config method
  2. Create a provider using the provider() function
  3. Pass two parameters to the provider() function: the name of the service and a function
  4. The provider function must contain a $get function
  5. 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:

Read full article on the Infragistics blog


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

One thought on “What is a Provider () in AngularJS?

  1. I was being asked in interview regarding the difference between provider, service and factory.

    1) In a Scenario, where we have to maintain the username and password after we successfully logged in into the system, which one is better to use? (provider, service or factory).

    2) Suppose, i have an bank account and after logged in into the account how do i maintain the account number through out the application? (Service, provider or factory)?

    Agnel.

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading