1

Ich injiziere $timeout in die folgende Direktive, aber es ist nicht definiert.

Der folgende Code druckt undefined an die Konsole und wirft Typeerror: $ Timeout keine Funktion ist;

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

Antwort

1

ich glaube, das Problem ist, dass Sie nichts Injektion, sind Sie nur einen Parameter angeben $timeout, die für einen Möchtegern-injizierten Dienst als wie ein Platzhalter fungiert. Um dies zu beheben, fügen Sie foo.$inject = ['$timeout']; bis zum Ende der Datei wie folgt:

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

Es gibt mehrere Beispiele here on the sitepoint site die auch einzeln die Injektion tun gehen aus der Klasse defintions.

Oder gehen durch die statische Fabrik (wie Sie wahrscheinlich beabsichtigt), es foo.factory.$inject = ['$timeout'] am Ende der Datei sein wird, und Sie werden auch Ihre Fabrik Funktion zu übernehmen und weitergeben eingespritzten Service zwicken müssen für Sie:

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