Angular 的新手,我正在尝试从一个单独的文件中注入(inject)常量。它似乎可以与 DI 一起使用,但是当我尝试使用它时,出现错误:错误:undefined is not an object (evaluating 'CApiEndpoints.authUrl')
。
我按照 Accessing AngularJS constants 中的建议尝试了点符号和方括号但继续出现错误。
文件包含在 index.html 中,DI 不会提示。
index.html
<script type="text/javascript" src="js/angular/constants.js"></script>
<script type="text/javascript" src="js/angular/app.js"></script>
js/angular/constants.js
var app = angular.module('appConst', []);
app.constant('CApiEndpoints', {
authUrl: 'http://api.example.com/v1/',
...
});
和我的 js/angular/app.js
var app = angular.module('app', ['ngRoute', 'ngCookies', 'appConst', 'appServices']);
app.controller('pageController', ['$scope', '$route', '$http', '$cookies', 'CApiEndpoints', function($scope, $route, $http, $cookies, $routeParams, $location, CApiEndpoints){
console.log(CApiEndpoints); // shows 'undefined'
$http({
method : 'GET',
url : CApiEndpoints.authUrl + 'user_info'
})
.then(
function successCallback(response) {
console.log(response);
},
function errorCallback(response) {
console.log(response);
});
}]);
如有任何帮助,我们将不胜感激。我搜索了过去 2 个小时,试图弄清楚这一点。
最佳答案
同时使用 DI inline array annotation 在 Controller 函数中注入(inject)依赖项,它们必须遵循它们在数组中的注入(inject)顺序。
如果你遵循上面的规则,你会发现你的函数中有两个额外的参数,所以你应该删除这两个不需要的 ($routeParams, $location
) 依赖。
app.controller('pageController', ['$scope', '$route', '$http', '$cookies', 'CApiEndpoints',
function($scope, $route, $http, $cookies, CApiEndpoints){
//controller code
}
]);
如果你没有错误地添加这些参数,你应该在函数和数组的两边添加这些参数。
app.controller('pageController', ['$scope', '$route', '$http', '$cookies', '$routeParams', '$location', 'CApiEndpoints',
function($scope, $route, $http, $cookies, $routeParams, $location CApiEndpoints){
//controller code
}
]);
关于javascript - AngularJS 常量未定义不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34598706/