2016-06-29 18 views
0

Ich arbeite an Angular Service. wo ich bin immer Fehler „Typeerror: this.testTwoFunction keine Funktion“ für die Funktion „testTwoFunction“AngularJS Service-Funktion nicht definiert

angular.module('MobileAppModule') 
.run([‘MyService’, function(MyService) 
{ 
    console.log("MyService in run"); 
    MyService.init(); 

}]) 
.service('MyService', ['$rootScope', function($rootScope) 
{ 

    this.init = function() { 
     testOneFunction(); 
    } 
    function testOneFunction() { 
     this. testTwoFunction() 
    } 

    this.testTwoFunction = function() { 

    } 

}]); 

Wie rufe ich die Funktion ‚testTwoFunction()‘

+0

tat Sie fixieren den Abstand zwischen "this" und "testTwoFunction()"? – devonJS

+0

ja, aber immer noch nicht funktionieren. – Rohit

Antwort

0

Dies bezieht dich auf „Heben“ . TLDR: testOneFunction ist eine Funktionsdeklaration, während testTwoFunction ein Funktionsausdruck ist (oder eine anonyme Funktion, die der Variablen "this.testTwoFunction" zugewiesen ist). Im gegebenen Fall benötigen Sie eine kleine Nachbestellung zu tun:

this.init = function() { 
    testOneFunction(); 
}; 

this.testTwoFunction = function() { 
    // doing something here 
}; 

function testOneFunction() { 
    this.testTwoFunction(); 
} 

Sie weitere Informationen hier über Scoping und Hebe lesen: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

0

versuchen mit diesem Code

(function() 
    {'use strict'; 
angular.module('MobileAppModule',[]) 
.run(['MyService', function(MyService) 
{ 
console.log("MyService in run"); 
MyService.init()}]) 
.service('MyService', ['$rootScope', function($rootScope) 
{ 
var self = this; 
self.init = function() { 
    testOneFunction(); 
} 
self.testTwoFunction = function() { 
    console.log("severice 2") 
} 
function testOneFunction() { 
    self.testTwoFunction(); 
} 
}]); 
})(); 
Verwandte Themen