gpt4 book ai didi

javascript - 为什么 "this"在带有 http promise 的 typescript 模块中未定义

转载 作者:搜寻专家 更新时间:2023-10-30 20:31:34 25 4
gpt4 key购买 nike

这是我的第一个 typescript 和 Angular 尝试,我被困在一个问题上。

我有一个按以下方式定义的模块 Controller (.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);
}
);
}
}
}

这是这个 Controller 所依赖的服务:

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

}
}
}

问题出现在 Controller 模块的以下行:

this.calBlock = response.data;

问题是 THIS 是未定义的,因此 calBlock 也是未定义的,jsConsole 会抛出一个错误:

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

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

我需要一种方法将 reponse.data(来自 $http 调用的 json 数组)分配给我的 Controller 的 typescript 类的 calBlock 属性。谁能帮我理解为什么 this 在响应函数中未定义以及我如何访问它?

谢谢

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

这里是重写的 calBlock 调用:

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

最佳答案

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

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

})

关于javascript - 为什么 "this"在带有 http promise 的 typescript 模块中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33851786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com