What is Provider in Angular Js?


What is Provider in Angular Js?

You can define Provider as service which is configurable and
which should be used when you want to expose an API for application-wide configuration that must be made before the application starts.
So technically speaking, it make sense during bootstrap(config) phase.

During application bootstrap, before AngularJS goes off creating all services, it configures and instantiates all providers. We call this the configuration phase of the application life-cycle. During this phase, services aren't accessible because they haven't been created yet.

Once the configuration phase is over, interaction with providers is disallowed and the process of creating services starts. We call this part of the application life-cycle the run phase.

So simply speaking there is no way to use any service in config phase except constant & Provider.

Technically, a Provider is defined as an object with a $get function.

Example -

So let suppose you want your application multilingual. And as know multlingual most  probably will be application wide. So when the application start initially then you might be interested to set the default language, so in that case using a Provider make sense.

So there are two ways for registering a  provider -

1. By usng $provide
var app = angular.module('app', []);

app.config(function($provide){
    $provide.provider(function(prefferedLang){
        return {
            $get: function() {
                return // prefferedLang
            }
        }
    })
})
2. We can simple use provider from module object, it's a syntactic sugar over $provide.provider
app.provider(function(prefferedLang){
    return {
        $get: function() {
            return // prefferedLang
        }
    }
})
So one should be interested in provider only if you want something to configure application wide.

Other examples like where you can use
- setting an API key for some third party resource.
- Configure $logger for system wide

Comments

Popular posts from this blog

What is MQTT protocol & its use

What the hack is Call, bind & apply

What is IIFE in Javascript ?