我试图在AngularJS中创建某种类型的发布/开发环境,这样我就可以轻松地部署版本,而无需通过多个文件来更改某些设置。
问题是我在我的app.js上明确声明了一个常量,以了解我实际使用的环境类型后得到一个未定义的变量。
控制台日志没有错误/日志。
App.js
angular.module('App', ['ionic', 'app.controllers', 'app.services', 'ngCordova'])
.constant('ENVIRONMENT', 'DEV')
.constant('baseServiceUrl', (function() {
alert(this.ENVIRONMENT); //outputs: undefined
return (this.ENVIRONMENT == 'DEV') ? 'api-dev.azureexample.com/' : 'api-release.azureexample.com/';
}) ())
.constant('apiAcessKey', (function() {
return (this.ENVIRONMENT == 'DEV') ? '?key=somekeyfordev' : '?key=somekeyforrelease';
}) ())
.run(function($ionicPlatform) {
/** some more code **/
那么,任何想法?
答案 0 :(得分:2)
constant
和value
服务应该包含常量,不能注入依赖项。 IIFE在这里
.constant('baseServiceUrl', (function() {
alert(this.ENVIRONMENT); //outputs: undefined
return (this.ENVIRONMENT == 'DEV') ? 'api-dev.azureexample.com/' : 'api-release.azureexample.com/';
}) ())
没有使用DI且不会this.ENVIRONMENT
,除非它是this
(window
)定义的。
constant
s的 constant
应在config
中定义:
app.config(($provide, ENVIRONMENT) => {
$provide.constant('baseServiceUrl', ENVIRONMENT == 'DEV'
? 'api-dev.azureexample.com/'
: 'api-release.azureexample.com/'
);
})
由于显然期望在运行阶段使用baseServiceUrl
和apiAcessKey
,因此将它们定义为factory
服务是恰当的:
app.factory('baseServiceUrl', (ENVIRONMENT) => {
return ENVIRONMENT == 'DEV'
? 'api-dev.azureexample.com/'
: 'api-release.azureexample.com/';
})
答案 1 :(得分:1)
您无法从常量中定义常量,但您可以使用服务来执行此操作...请参阅working plunker.
以下是代码:
angular.module('plunker', [])
.constant('ENVIRONMENT', 'DEV')
.service('urls',function(ENVIRONMENT){ this.apiUrl = (ENVIRONMENT == 'DEV') ? 'api-dev.azureexample.com/' : 'api-release.azureexample.com/';
})
.controller('MainCtrl', function($scope, urls) {
$scope.name = urls.apiUrl;
});
我的应用只显示网址:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</body>
</html>
为什么不能从常量中定义常量?如果你想创建一个依赖于常数B的常数A,你需要使用依赖注入来告诉A取决于B的角度。但是常量没有依赖性,这就是我使用服务而不是允许定义依赖的原因。