user3052526
user3052526

Reputation: 681

Typescript AngularJS Scope Issue

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.

Upvotes: 2

Views: 100

Answers (1)

dfsq
dfsq

Reputation: 193261

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

Upvotes: 2

Related Questions