【问题标题】:AngularJS: Injecting $timeout not available in directiveAngularJS:注入 $timeout 在指令中不可用
【发布时间】:2017-02-12 13:14:38
【问题描述】:

我将$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;
    }
}

【问题讨论】:

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


    【解决方案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'];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 2014-12-04
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多