0

I have a service that make a REST call. When the rest call is complete (i.e. the data is available), I want to call the service's function which process that data.

.service('EventService', function(eventRestApi, $scope) { 
     var internalData = { messages : [], headers: [], consolidatedEvents : {} }
     return {    
         loadEvents : function(beginTimeMillis, endTimeMillis) { 
            this.getEvents(beginTimeMillis, endTimeMillis, internalData, null)
                .then(function(result){
                    internalData.consolidatedEvents = this.consolidateEvents(internalData.events)
                })  
         },
         getEvents : function() {...},
         consolidatedEvents : function() {...},
     }

I get an error saying that this doesn't have consolidateEvents. How do I access a function in my service on a callback? Am I approaching this problem wrong?

1 Answer 1

2

In a callback, 'this' become your callback, so to access it you can link the parent scope in a variable.

I recommend that :

.service('MyService', function () {
    var that = this;
    return {
            myCallback : function () {
                    that.myMethod();
            }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.