2

I have the following Typescript:

module MainCtrl {
    interface IMainController {
        getCustomers(): any;
    }

    class MainController implements IMainController {
        static $inject = ['$scope', 'ApiServices','RememberSrvc'];
        constructor(private $scope: any,
                private ApiServices: ApiServices.IApiService,
                private RememberSrvc: RememberSrvc.IRememberService) {
            var vm = this;

        }

        getCustomers(){

            this.ApiServices.get_request_params(, "")
                .then(function(data) {
                    this.RememberSrvc.remember(data);//this is not working
                }, function(err) {

                });

            }

    }

    angular.module('app').controller('MainCtrl', MainController);
}

I cannot access the RememberSrvc from the then block. And although I can console.log the response. I cannot bind data to my view.

1
  • Typescript throws an error if i have it directly or with a vm Commented Dec 5, 2015 at 14:27

1 Answer 1

2

You can use arrow function to keep lexical scope:

getCustomers() {
    this.ApiServices.get_request_params(, "")
        .then(data => this.RememberSrvc.remember(data), function (err) {
            // handle error
        });
}

Or you could also bind context explicitly:

this.ApiServices.get_request_params(, "")
    .then(this.RememberSrvc.remember.bind(this), function (err) {
        // handle error
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Dude those both methods worked, how was i missing this. had been trying to solve it for 2.5 hours now. Thanks mate

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.