Angularjs:如何使服务/工厂从提供者

时间:2016-08-31 07:55:31

标签: angularjs

我真的想了解提供商配置如何工作..我有一个只进行http调用的服务。让我们说它是这样的:

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

我知道提供程序设置了provider配方,但到目前为止我看到的所有示例还没有告诉我他们如何向工厂和服务提供配置的数据。

目前我只想要一个简单的数据可用于整个模块,可以配置。

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

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

这里是一个非常简单的例子(不完全是提供者如何工作)我想如何配置提供者的数据,这些数据将用于注册到模块的所有服务和工厂。那么,我怎样才能从服务提供商那里获取数据集?

1 个答案:

答案 0 :(得分:1)

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
    }
});