Oscar Reyes
Oscar Reyes

Reputation: 4342

Angularjs: How to make service/factory get data from provider

I am really trying to understand how provider configuration works.. i have a service which only makes http calls. let's say it goes like this:

module.service("$myService", ["$http", function($http){
    this.get = function(url, headers){
        return $http({
            method: "GET",
            url: url,
            headers: headers || {}
        });
    };
}]);

i know providers are set with the provider recipe, but all the examples i have seen so far have not yet cleared me on how they can provide the configured data to factories and services.

for the moment i just want a simple data to be available to the whole module which can be configured.

module.provider("myProvider", [function(){
    return {
        setDomain: function(value){
            this.Domain = value
        }
    }
}]);

module.config(["myProvider", function($myProvider){
    $myProvider.setDomain("localhost");
}]);

in here is quite a simple example (not exactly how provider works) on how i would like to configure the provider with the data which will be used to all services and factories registered to the module. So again, how could i make the data set from providers be accesible from the services/factories?

Upvotes: 0

Views: 68

Answers (1)

Estus Flask
Estus Flask

Reputation: 222369

There are only two basic types of services in Angular - constant and provider. All other types of services are derivatives of provider.

service and factory are syntactic sugar for provider. They are supposed to be used when service provider shouldn't be configured. And provider is supposed to be used instead when service provider should be configured. Thus, provider is responsible for configuring it's own provider only.

For your case

i just want a simple data to be available to the whole module which can be configured.

constant service is a match, this is what it is for. It can't have dependencies but is available for injection in both config and run phases.

module.constant("myConstant", {
    setDomain: function(value){
        this.Domain = value
    }
});

Upvotes: 1

Related Questions