Suavelizard
Suavelizard

Reputation: 148

How to inject dependency in Angular 1.5 component generated by Angular-Fullstack

I have used the Yeoman Angular-Fullstack generator to create a new component and I am attempting to inject the Modal service into it.

ng-annotate is being used to inject the service however I get this:

Error: [$injector:strictdi] CampaignsComponent is not using explicit annotation and cannot be invoked in strict mode

The controller looks like so:

'use strict';
const angular = require('angular');
const uiRouter = require('angular-ui-router');
import routes from './campaigns.routes';

export class CampaignsComponent {
  /*@ngInject*/
  constructor(Modal) {
    console.log('campaigns');
          this.confirmDelete = Modal.confirm.delete();

  }
}
// CampaignsComponent.$inject['Modal'];
export default angular.module('myApp.campaigns', [uiRouter])
  .config(routes)
  .component('campaigns', {
    template: require('./campaigns.html'),
    controller: CampaignsComponent,
    controllerAs: 'campaignsCtrl'
  })
  .name;

The generator automatically scaffolds out a Component that looks like so:

import angular from 'angular';
import uiRouter from 'angular-ui-router';
import routing from './main.routes';

export class MainController {

  /*@ngInject*/
  constructor($http) {
    this.$http = $http;
    console.log('main')
  }

  $onInit() {
    this.$http.get('/api/things')
      .then(response => {
        this.awesomeThings = response.data;
      });
  }

  addThing() {
    if (this.newThing) {
      this.$http.post('/api/things', {
        name: this.newThing
      });
      this.newThing = '';
    }
  }

  deleteThing(thing) {
    this.$http.delete('/api/things/' + thing._id);
  }
}

export default angular.module('myApp.main', [uiRouter])
  .config(routing)
  .component('main', {
    template: require('./main.html'),
    controller: MainController
  })
  .name;

Attempting to inject $http into the Campaigns controller like

  /*@ngInject*/
  constructor($http) {
    this.$http = $http;
    console.log('main')
  }

still causes the same error so it's not down to the Modal service at this point and I am completely stumped.

Upvotes: 3

Views: 825

Answers (2)

hopkinsrush
hopkinsrush

Reputation: 471

Add the following method to your MainController class:

$onInit(){}

Upvotes: 0

Yunhan Li
Yunhan Li

Reputation: 153

You can fix this error by using $inject property. Basically, the solution to your problem is to inject the '$http' dependency.

CampaignsComponent.$inject['$http'];

This error occurs when attempting to invoke a function or provider which has not been explicitly annotated, while the application is running with strict-di mode enabled. You can read the details here.

Upvotes: 0

Related Questions