[英]Application wide constants in Angularjs
We have an API that requires an application id be included with every request. 我们有一个API,要求每个请求都包含一个应用程序ID。 I'd like for this id to be accessible in every controller and I'd ideally like to only set it once. 我希望此ID在每个控制器中都可以访问,并且理想情况下,我只希望设置一次。 I can set it at the top level by doing: 我可以通过以下操作将其设置为最高级别:
angular.module('applicationName',
['controller1', 'controller2', 'controller3'])
.constant('APPLICATION_ID', '12345abcde');
But I'd like to be able to access it in controller1/2/3. 但是我希望能够在controller1 / 2/3中访问它。 What's the best way to set the APPLICATION_ID variable so it's available in all components of the application? 设置APPLICATION_ID变量以便在应用程序的所有组件中可用的最佳方法是什么?
angular.module('applicationName',
['controller1', 'controller2', 'controller3'])
.constant('APPLICATION_ID', '12345abcde');
And then in your controller 然后在您的控制器中
application.controller('myController',
['$scope','APPLICATION_ID',function($scope,applicationId)
{
console.log("app id="+applicationId);
}]);
Since you need to send the Application_ID
with every request to your api, as mentioned in the comments, you can modify the $http
service to add the ID. 如注释中所述,由于需要将每个请求的Application_ID
发送到您的api,因此可以修改$http
服务以添加ID。
Define the constant 定义常数
angular.module('myModule')
.constant('APPLICATION_ID', 'foobarbaz');
Inject the constant into your $http
service to send with every request. 将常量注入您的$http
服务,以随每个请求发送。
angular
.module('myModule')
.config(httpConfig);
httpConfig.$inject = ['$httpProvider', '$provide'];
function httpConfig($httpProvider, $provide) {
$provide.factory('httpInterceptor', ['APPLICATION_ID', function (APPLICATION_ID) {
return {
request: function (config) {
// APPLICATION_ID can now be used in all your requests
// Example:
// To URL: GET /api/v1/users?appid=foobarbaz
if (config.mehtod === 'GET') {
var sep = config.url.indexOf('?') === -1 ? '?' : '&';
config.url = config.url + sep + 'appid=' + APPLICATION_ID;
}
return config;
}
};
}]);
}
$httpProvider.interceptors.push('httpInterceptor');
Now you can use the Application_ID
in all of your requests without the need to inject it into all of your controllers. 现在,您可以在所有请求中使用Application_ID
,而无需将其注入到所有控制器中。
Resources 资源资源
https://docs.angularjs.org/api/ng/service/ $http https://docs.angularjs.org/api/ng/service/ $ http
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.