我想开发一个 AngularJS Web 客户端,其 REST 后端可能位于不同的服务器上。
所以基本上我想在前端有一个属性输入字段,对于每个 session ,我将输入基本 REST url(例如 http://localhost:8080/backend/rest/
)
是否有某种最佳实践能够在所有 Controller /工厂/服务之间共享基本 URL,以便将其包含在所有 $http 请求中?
最佳答案
我会配置一个 HTTP request interceptor 服务,它会简单地将值添加到传递给 $http 服务的 URL 中。类似于以下内容(未测试):
// register the interceptor as a service
$provide.factory('pathPrependerInterceptor', function() {
var _path = 'http://localhost:8080/backend/rest'; // default value
return {
request: function(config) {
config.url = _path + config.url
return config;
},
setPath: function(path) {
_path = path;
}
}
});
$httpProvider.interceptors.push('pathPrependerInterceptor');
关于AngularJS 远程客户端属性共享到 Controller /服务,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21971516/