AngularJS:在指令中注入$ timeout不可用

时间:2017-02-12 13:14:39

标签: javascript angularjs angularjs-directive ecmascript-6 angularjs-timeout

我将$timeout注入以下指令但未定义。

以下代码将 undefined 打印到控制台并抛出 TypeError:$ timeout不是函数;

export default class foo {
    constructor ($timeout) {
        'ngInject';
        this.restrict = 'A';
        this.scope = {};
        this.$timeout = $timeout;

        console.log( $timeout );
        $timeout( function() {
            alert('timeout');
        }, 0 );
    }

    link($scope, $element, $attrs, $ctrl ) {      
        ....
    }

    // Create an instance so that we can access this inside link
    static factory() {
        foo.instance = new foo();
        return foo.instance;
    }
}

1 个答案:

答案 0 :(得分:1)

我认为问题在于你没有注入任何东西,你只是指定一个参数$timeout,它就像一个注入服务的占位符一样。要解决此问题,请将foo.$inject = ['$timeout'];添加到文件末尾,如下所示:

export default class foo {
    constructor ($timeout) {
        'ngInject';
        this.restrict = 'A';
        this.scope = {};
        this.$timeout = $timeout;

        console.log( $timeout );
        $timeout( function() {
            alert('timeout');
        }, 0 );
    }

    link($scope, $element, $attrs, $ctrl) {      

    }

    // Create an instance so that we can access this inside link
    static factory() {
        foo.instance = new foo();
        return foo.instance;
    }
}

foo.$inject = ['$timeout'];

有几个例子here on the sitepoint site,它们也继续与类定义分开进行注射。

或者通过静态工厂(正如您可能想要的那样),文件末尾将是foo.factory.$inject = ['$timeout'],您还必须调整工厂功能接受并传递注入的服务:

export default class foo {
    constructor ($timeout) {
        'ngInject';
        this.restrict = 'A';
        this.scope = {};
        this.$timeout = $timeout;

        console.log( $timeout );
        $timeout( function() {
            alert('timeout');
        }, 0 );
    }

    link($scope, $element, $attrs, $ctrl ) {      

    }

    // Create an instance so that we can access this inside link
    static factory($timeout) {
        foo.instance = new foo($timeout);
        return foo.instance;
    }
}

foo.factory.$inject = ['$timeout'];