-1

I'm trying to write a quick test that uses ES6 and Angular to call an API - but I can't quite work out how to scope the injected values into the callbacks - in all cases they seem to be completely isolated. Any suggestions??

class Test {

constructor($state) {
    this.$state = $state;
}

doThing() {
    var request = this.$http({
        method: "get",
        url: "https://blah,
        params: {
            action: "get"
        }
    });
    return ( request.then(this.handleSuccess, this.handleError) );
}

handleSuccess(response) {
    update $state...
    this.$state is undefined
    this is undefined
}

handleError(response) {
    update $state...
}
}

Test.$inject = ['$state'];
Silver
  • 4,911
  • 3
  • 15
  • 16
  • it'l be undefined or window, because you're passing the functions into .then without binding them back to `this`. – Kevin B Jan 06 '16 at 05:04
  • But how do I bind them back to this? The $http version of then doesn't have a bind method? – Silver Jan 06 '16 at 10:53
  • 1
    Possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Felix Kling Jan 06 '16 at 13:27

1 Answers1

0

Excellent link from Felix got me to where I need to be - not 100% confident this is the best way, but it's at least reasonably clean. HandleSuccess & HandleError were also changed to accept an optional scope.

    return ( request.then((response)=> {
        this.handleSuccess(response, this)
    }).catch((response)=> {
        this.handleError(response, this)
    }));
Silver
  • 4,911
  • 3
  • 15
  • 16