Charles Watson Charles Watson - 4 months ago 16
AngularJS Question

ES6 angular service module not being passed around correctly?

Using Angular 1.5 with ES6 classes, I have an operating application.

I created a service:

class EnterpriseService {
/*@ngInject*/
constructor($http) {
this.http = $http;
};

getData() {
return this.http.get('http://localhost:3000/').then(function(response) {
return response;
});
}
}

EnterpriseService.$inject = ["$http"];
export default EnterpriseService;


And I inject it into my controller:

class EnterpriseController {
/*@ngInject*/
constructor(EnterpriseService, $scope) {
this.name = 'enterprise';
this.systemId = 20003
this.pageLink = '#/enterprise';
this.EnterpriseService = EnterpriseService;
this.getEnterpriseData();
this.scope = $scope;
console.log(this.EnterpriseService);
}

getEnterpriseData() {
scope.stores = this.EnterpriseService.getData();
}
}

EnterpriseController.$inject = ["EnterpriseService", "$scope"];
export default EnterpriseController;


I am importing the service into my component file that bootstraps the overall component:

import template from './enterprise.html';
import controller from './enterprise.controller';
import './enterprise.less';
import servicesModule from './enterprise.service';

let enterpriseComponent = function () {
return {
restrict: 'E',
scope: {},
template,
controller,
controllerAs: 'vm',
bindToController: true
};
};

export default enterpriseComponent;


As of now, I get the infamous unknown service provider error. My assumption is that it has to do with the fact that I never instantiate my service class as an Angular service by including it on an Angular module, ie:
angular.module('enterpriseService', enterpriseService)


But I'm not sure how to go about doing that in this ES6 environment.

Should there be another single file that bootstraps all service modules that then gets included? What exactly would that look like?

Answer

It looks like you're trying to call the function which uses "$scope" before scope is saved off. Try moving the line this.scope = $scope; above this.getEnterpriseData(): in your code here:

class EnterpriseController {
  /*@ngInject*/
  constructor(enterpriseService, $scope) {
    this.name = 'enterprise';
    this.systemId = 20003
    this.pageLink = '#/enterprise';
    this.EnterpriseService = EnterpriseService;
    this.getEnterpriseData();
    this.scope = $scope;
    console.log(this.EnterpriseService);
  }

It should look like this:

class EnterpriseController {
  /*@ngInject*/
  constructor(enterpriseService, $scope) {
    this.name = 'enterprise';
    this.systemId = 20003
    this.pageLink = '#/enterprise';
    this.EnterpriseService = EnterpriseService;
    this.scope = $scope;
    this.getEnterpriseData();
    console.log(this.EnterpriseService);
  }