1

我正在注入$timeout以下指令,但未定义。

以下代码将undefined打印到控制台并抛出TypeError: $timeout is not a function ;

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;
    }
}
4

1 回答 1

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

在 sitepoint 站点上有几个示例,它们也继续与类定义分开进行注入。

或者通过静态工厂(正如您可能想要的那样),它将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'];
于 2017-02-12T13:42:04.113 回答