跨Angular服务的全球客户? [英] Globals across Angular services?

查看:42
本文介绍了跨Angular服务的全球客户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有几个服务,它们向同一URL根的各个端点发出http请求.我希望能够更改此根.

For example, I have several services that make http requests to various endpoints of the same url root. I would like to be able to change this root.

我的服务模块如下.

var host = 'http://my-api.com'; 
return {
get: function(id) {
    return $http({
        url: host + '/contacts/' + id,
        method: 'GET'
      });
},
...
switchHost: function(url){
    host = url;
}
});

因此,我可以在控制器中调用 ContactService.switchHost('http://new-url')来更新此特定服务.

So I can call ContactService.switchHost('http://new-url') in my Controllers to update this particular Service.

我想拥有某种 Root Service ,可以在其中全局定义 host switchHost .

I would like to have some sort of Root Service where I coul define host and switchHost globally.

注意:这里的用例是我们的某些客户将访问我们公司的API,而其他客户将自托管其资源.

Note: The use case here is that some of our clients will be accessing our company API, and others will be self-hosting their resources.

推荐答案

我建议您创建一个拦截器,该拦截器将像这样消化一个角度值.

i suggest you to create an interceptor which will digest an angular value like this.

angular.module('...')
.value('HOST', 'http://www.fu.bar.com/')
.factory('InterceptorFactory', function (HOST) {
    return {
        request: function(config) {

            config.url = HOST + config.url;

            return config;
        }
    };
})
.config(['$httpProvider',function($httpProvider) {


    $httpProvider.interceptors.push('InterceptorFactory');
}]);

无论何时调用$ http服务,工厂都会被调用并添加您的主机.如果要更新主机,则只需在任何块中插入值并更新它即可.

Whenever you call the $http service, the factory will be called and will add your host. If you want to update the host, you just need to inject in any block the value and update it.

这篇关于跨Angular服务的全球客户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆