javascript - Globals across Angular services? -


can define global variables or functions can accessed of angular service modules?

for example, have several services make http requests various endpoints of same url root. able change root.

my service modules this.

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

so can call contactservice.switchhost('http://new-url') in controllers update particular service.

i have sort of root service coul define host , switchhost globally.

note: use case here of our clients accessing our company api, , others self-hosting resources.

i suggest create interceptor digest angular value 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'); }]); 

whenever call $http service, factory called , add host. if want update host, need inject in block value , update it.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -