Search code examples
angularjsecmascript-6es6-promiseangularjs-http

Scope of $http callback in ES6


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'];

Solution

  • 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)
        }));