0

I'm storing an object inside of the service in my angular app, I can't access 'this' from within the callback method. Something like this...

    app.service("myService", ['$http', '$q', 
        function($http, $q) {
            return ({foo: foo});

            this.myObj = {};

          function doSomething(param, callback){
            param++;
            callback(param);
          } 

          function foo(param){
          doSomething(param, function(responce){ 
            this.myObj.myParam = responce;//'this' is undefined
          });
          }
     });

How do I access it correctly? Thank you...

Uliana Pavelko
  • 2,824
  • 28
  • 32

3 Answers3

1

'this' is only kept in current scope of the function. when called inside a new function 'this' changes. what most people do is var that = this;

 app.service("myService", ['$http', '$q', 
    function($http, $q) {
        var that = this;

        return ({foo: foo});

        this.myObj = {};

      function doSomething(param, callback){
        param++;
        callback(param);
      } 

      function foo(param){
        doSomething(param, function(responce){ 
          that.myObj.myParam = responce;//'that' defined
        });
      }
 });
d3l33t
  • 890
  • 6
  • 10
0

If obj is the object you want to be the this, you can use bind to set it as the actual this for the function f, as an example: f.bind(obj).

As from the documentation:

The bind() method creates a new function that, when called, has its this keyword set to the provided value [...]

skypjack
  • 49,335
  • 19
  • 95
  • 187
0

You should store first "this" object into some variable. And you should use it inside callback function.

app.service("myService", ['$http', '$q', 
    function($http, $q) {
        return ({foo: foo});
        var self = this;
        self.myObj = {};

      function doSomething(param, callback){
        param++;
        callback(param);
      } 

      function foo(param){
      doSomething(param, function(responce){ 
        self.myObj.myParam = responce;
      });
      }
 });

I wish it helped you.