[英]setup $http url from .properties file in angularjs
I have some services in my App. 我的应用程序中有一些服务。
loginApp.factory('urlService', function() {
return {
baseUrl : function(){
return 'http://localhost:8080/myAppName'
}
}
});
consume this service by one another services. 互相使用这项服务。
loginApp.factory('loginServices', function($http,urlService) {
return {
loginAuth : function(aut,resp){
return $http({
method: 'GET',
url: urlService.baseUrl()+'auth',
}).success(function(result) {
return result;
});
}
}
});
I want configure http://localhost:8080/myAppName
from a .properties file which is present on application root. 我想从应用程序根目录中存在的.properties文件配置
http://localhost:8080/myAppName
。
You can do some thing like this 你可以做这样的事情
angular.module('app.properties', []).provider('properties', function() {
var resource;
$.ajax({
url: 'properties.json',
dataType: 'json',
async: false,
success: function(data) {
resource = data;
}
});
this.properties= resource;
this.$get = function() {
return this.properties;
};
});
Then use this provider in you controller/services to access the properties 然后在控制器/服务中使用此提供程序来访问属性
angular.module('loginApp', ['app.properties']).factory('urlService', function(properties) {
return {
baseUrl : function(){
return properties.baseUrl;
}
}
});
And your properties.json should be like 而且你的properties.json应该像
{
"baseUrl" :"http://localhost:8080/myAppName"
}
NB : I have used jquery ajax to load the properties.json because it should not be an async call, so I set async: false 注意:我已经使用jquery ajax加载了properties.json,因为它不应该是异步调用,所以我设置了async:false
$.ajax({
url: 'properties.json',
dataType: 'json',
**async: false**,
success: function(data) {
resource = data;
}
});
I think the best option in that case would be to create a service that then can be injected and in that service pull the config file and assign content to a returned variable (hope it makes sense so far) 我认为在这种情况下,最好的选择是创建一个服务,然后可以将其注入,并在该服务中提取配置文件并将内容分配给返回的变量(希望到目前为止是有意义的)
Although that will leave you with possible race issues when ie your loginService
will be called before config was loaded but if you make a good use of promises all this will be trivial for you 虽然这会在可能出现种族问题,
loginService
在加载配置之前调用loginService
但是如果您充分利用了loginService
,那么所有这些对您来说都是微不足道的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.