javascript - AngularJS 常量未定义不是对象

标签 javascript angularjs dependency-injection angularjs-controller

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/

相关文章:

javascript - 在 typescript 中扩展 Angular 全局对象

javascript - 未获取表中的表达式值

javascript - 我们如何在 Angularjs 指令之外使用 $compile

ios - Swift - 闭合模式

spring - Autowire Spring bean 实现两个接口(interface)

javascript - 将功能注入(inject)其他 Node.js 模块

java - 我如何在opengl中画一个半圆

javascript - Ace 编辑器,如何删除除一个之外的所有 keyBindings?

javascript - JQuery 自动完成,并在字段内提供提示

javascript - AngularJS 中 $http 的 HTTP JSONP 请求问题