typescript 为什么在带有 http 承诺的打字稿模块中未定义“this”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33851786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:08:16  来源:igfitidea点击:

why "this" is undefined in typescript module with http promise

javascriptangularjstypescript

提问by J King

this is my first typescript and angular attempt and I am stuck on one problem.

这是我的第一次打字稿和角度尝试,但我遇到了一个问题。

I have a module controller defined in the following way (.ts file):

我有一个以下列方式定义的模块控制器(.ts 文件):

module app.controllers {
    "use strict"

    import services = app.services;

    export class calendarController {

        calBlock: any;
        deptId: number;
        calSvc: app.services.calendarService;

        static $inject = ["$scope", "calendarService"];

        constructor(isolateScope: directives.calendarScope, calSvc: services.calendarService) {

            this.deptId = isolateScope.deptId;
            this.calSvc = calSvc;

            calSvc.getMonthBlock(12, 2015, 1, this.deptId)
            .then(
                function (response) {
                    //promise fullfilled (regardless of outcome)                
                    this.calBlock = response.data;
                 },
                 function (error) {
                //handle errors
                    alert(error);
                 }   
             );
        }
    }
}

Here is the service this controller is dependant on:

这是该控制器所依赖的服务:

module app.services {
    "use strict"
    export class calendarService {

        private _http: ng.IHttpService;

        static $inject = ["$http"];

        constructor(http: ng.IHttpService) {
            this._http = http;            
        }

        getMonthBlock = function (month:number, year:number, calId:number, deptId:number) {

            //initialise service url
            var sURL = _sf.getServiceRoot('KrisisShifts') + "CalendarService/GetMonthCal/" + calId + "/" + deptId + "/" + month + "/" + year;
            //create config object for get function
            var config = {
                URL: sURL,
                method: "GET",
                dataType: 'json',
                headers: {
                    'ModuleId': _sf.getModuleId(),
                    'TabId': _sf.getTabId(),
                    'RequestVerificationToken': _sf.getAntiForgeryValue()
                }
            }
            //return the promise of the http.get function
            return this._http.get(sURL, config);

        }
    }
}

The problem occurs on the following line of the controller module:

问题出现在控制器模块的以下行上:

this.calBlock = response.data;

The problem is that THISis undefined so therefore calBlock is also undefined and the jsConsole throws an error:

问题是THIS未定义,因此 calBlock 也未定义,并且 jsConsole 抛出错误:

TypeError: Cannot set property 'calBlock' of undefined at shift-calendar-controller.js?cdv=28:14

类型错误:无法在 shift-calendar-controller.js?cdv=28:14 设置未定义的属性“calBlock”

I am relativly new to javascript and angular and typescript so I am having trouble figuring out why "this" is undefined. I think its because its enclosed in a function.

我对 javascript、angular 和 typescript 比较陌生,所以我无法弄清楚为什么“ this”是未定义的。我认为这是因为它包含在一个函数中。

I need a way to assign the reponse.data (a json array from a $http call) to the calBlock property of the typescript class for my controller. Can someone help me understand why thisis undefined within the response function and how I can access it?

我需要一种方法将 reponse.data(来自 $http 调用的 json 数组)分配给我的控制器的 typescript 类的 calBlock 属性。有人能帮助我理解为什么是响应函数内不定,我怎么能访问它?

Thanks

谢谢

EDIT: SOLUTION BASED ON tymeJV's answer

编辑:基于 tymeJV 回答的解决方案

here is the re-written calBlock call:

这是重写的 calBlock 调用:

            calSvc.getMonthBlock(12, 2015, 1, this.deptId)
            .then((response) => {
                    //promise fullfilled (regardless of outcome)                
                    this.calBlock = response.data;
                },
            (error) => {
                    //handle errors
                    alert(error);
                }   
            );

回答by tymeJV

Because the context of thisis lost in the callback. Use arrow functions in typescript to preserve the context!

因为 的上下文this在回调中丢失了。在打字稿中使用箭头函数来保留上下文!

calSvc.getMonthBlock(12, 2015, 1, this.deptId).then((response) => {

})