【问题标题】:How to inject service into directive in AngularJS with ES6如何使用 ES6 将服务注入到 AngularJS 中的指令中
【发布时间】:2017-08-08 22:13:56
【问题描述】:

这是我的指令索引:

'use strict';

import SignupService from './core/services/signup.service';

import FooterDirective from './components/footer/footer.directive';
import MenuDirective from './components/menu/menu.directive';

export default angular.module('index.components', [])
    .directive('footer', FooterDirective)
    .directive('menu', [MenuDirective, function(SignupService) {}]);

和指令:

import tmpl from './menu.tpl.html';

class Menu {
    constructor($scope) {
        this.scope = $scope;
        this.restrict = 'AC';
        this.transclude = true;
        this.replace = true;
        this.templateUrl = tmpl;
        this.scope = {
            ngSrc: "@",
        };
    }

    link(scope, elem, attrs) {

        console.log(scope.SignupService);

        scope.logoutCall = () => {
            this.SignupService.logoutSubmit();
        }
    }
}
function factory() {
    "ngInject";

    return new Menu(...arguments);
}

export default factory;

我需要从 Menu 指令访问 Signup Service,但我有这个错误 - Incorrect injection token! Expected service name as string, got function factory()。向指令注入服务的最佳实践是如何以及什么是最佳实践。谢谢凝胶。

【问题讨论】:

    标签: javascript angularjs service components directive


    【解决方案1】:

    您的依赖注入似乎是错误的。

    代替

    .directive('menu', [MenuDirective, function(SignupService) {}]);
    

    应该有

    .directive('menu', ['SignupService', function(SignupService) {}]);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    相关资源
    最近更新 更多