【问题标题】:How to inject dependency in Angular 1.5 component generated by Angular-Fullstack如何在 Angular-Fullstack 生成的 Angular 1.5 组件中注入依赖项
【发布时间】:2016-12-21 13:37:52
【问题描述】:

我已经使用 Yeoman Angular-Fullstack 生成器创建了一个新组件,并尝试将 Modal 服务注入其中。

ng-annotate 被用来注入服务但是我得到了这个:

错误:[$injector:strictdi] CampaignsComponent 未使用显式注释,无法在严格模式下调用

控制器如下所示:

'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;

生成器会自动搭建一个如下所示的组件:

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;

尝试将 $http 注入到 Campaigns 控制器中,例如

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

仍然会导致同样的错误,所以此时它还没有归结为模态服务,我完全被难住了。

【问题讨论】:

  • 你找到解决办法了吗?
  • 很遗憾没有。我最终避免使用 ng-inject 注释。
  • 我通过使用 require('./path to file') 解决了这个问题。例如,当您加载 app.services 模块,然后在单独的文件中定义了不同的服务(工厂)时,在定义 app.services 模块的文件中,您可以在文件末尾写入 require('./path归档'),效果很好

标签: angularjs service components angular-fullstack


【解决方案1】:

您可以使用$inject 属性修复此错误。基本上,您的问题的解决方案是注入 '$http' 依赖项。

CampaignsComponent.$inject['$http'];

当应用程序在启用 strict-di 模式的情况下尝试调用未显式注释的函数或提供程序时,会发生此错误。您可以阅读详细信息here

【讨论】:

    【解决方案2】:

    将以下方法添加到您的 MainController 类中:

    $onInit(){}
    

    【讨论】:

      猜你喜欢
      • 2016-09-15
      • 2016-09-10
      • 2018-06-10
      • 1970-01-01
      • 2016-09-14
      • 2016-04-25
      • 1970-01-01
      • 2015-05-18
      • 2016-05-05
      相关资源
      最近更新 更多