简体   繁体   中英

AngularJS: TypeError: Cannot read property 'get' of undefined?

My App looks like

var app = angular.module('cockpit', ['tenantService', 'ngMaterial', 'ngMdIcons']);

My controller looks like

angular.module('cockpit').controller('TenantController', ['TenantService', function($scope, TenantService){
  $scope.tenants = TenantService.get();
  console.log('TenantController started', $scope.tenants);
}]);

and my service looks like

angular.module('tenantService', [])
  .service('TenantService', function () {
    this.get = function() {
      return [
        {
          'name': 'fakeTenant',
          'freeMemory': '45',
        },
      ]
    }
});

I import the dependencies correctly as

  <script src="src/cockpit/app.js"></script>
  <script src="src/cockpit/controllers/tenant_controller.js"></script>
  <script src="src/cockpit/services/tenants.js"></script>

and in my HTML , I do

      <div ng-controller="TenantController">
        {{tenants}}
      </div>

But when I see console I see

TypeError: Cannot read property 'get' of undefined
    at new <anonymous> (tenant_controller.js:2)
    at Object.e [as invoke] (angular.js:4169)
    at G.instance (angular.js:8422)
    at angular.js:7677
    at r (angular.js:330)
    at J (angular.js:7676)
    at g (angular.js:7062)
    at J (angular.js:7701)
    at g (angular.js:7062)
    at g (angular.js:7065)

Why is the dependency not injected?

The problem was injection at controller, the following fixed it

angular.module('cockpit').controller('TenantController', function($scope, TenantService){
  $scope.tenants = TenantService.get();
  console.log('TenantController started', $scope.tenants);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM