Lloyd Banks
Lloyd Banks

Reputation: 36699

AngularJS - Calling Service Function From the Same Service

I have the following service:

myApp.service('myService', function(){

    this.functionOne = function(){
         return true;
    };

    this.functionTwo = function(){
         // Call functionOne
    };

});

I would like to call functionOne from functionTwo without having to rewrite the way the service is written (in this case, returning an object with functions).

Is there a way to do this using the this format of providing functions?

Upvotes: 0

Views: 1272

Answers (2)

nairys
nairys

Reputation: 343

app.factory('myService', function() {
  var firstFn = function() {
    secondFn();
    //some code
  }

  var secondFn = function() {
     //additional code
  }

  return {
    firstFn: firstFn;
  }

})

This code exposes the firstFn to wherever this service gets called. When you call firstFn, it will also run secondFn. You can access firstFn using myService.firstFn() whenever you inject this service. Hope that helps.

Note: I've used a factory instead of a service. There's a subtle yet significant difference between the two. Long story short, a factory is a bit more flexible than a service with respect to what you can do with it.

Upvotes: 0

Reactgular
Reactgular

Reputation: 54821

There are multiple ways to do this, but the safest is to just define a _this variable.

myApp.service('myService', function(){
   var _this = this;
   this.functionOne = function(){
        return true;
   };

   this.functionTwo = function(){
        var x = _this.functionOne();
   };
});

In this case the variable _this references the myService object that is created by AngularJS.

The problem here is that this is a JavaScript special variable that can be assigned values. It doesn't work like it does in other languages. So unless you know what the this variable will be at the time of the closure functions execution you should just use a variable you know is safe.

Upvotes: 1

Related Questions