1

Я вводил $timeout в следующую директиву, но не определен.

Следующие печатает код неопределенными на консоль и бросает TypeError: $ таймаут не является функцией;

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

Я думаю, что проблема в том, что вы ничего не закачивание, вы просто указать параметр $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'];