Typescript AngularJS范围问题

时间:2015-12-05 14:17:51

标签: angularjs 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);
}

我无法从RememberSrvc块访问then。虽然我可以console.log响应。我无法将数据绑定到我的视图。

1 个答案:

答案 0 :(得分:2)

您可以使用箭头功能来保持词汇范围:

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

或者你也可以明确地绑定上下文:

this.ApiServices.get_request_params(, "")
    .then(this.RememberSrvc.remember.bind(this), function (err) {
        // handle error
    });