javascript - por que "this" está indefinido em um módulo TypeScript com promessa HTTP
esta é minha primeira tentativa com TypeScript e Angular e estou preso em um problema.
Eu tenho um controlador de módulo definido da seguinte maneira (arquivo .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);
}
);
}
}
}
Aqui está o serviço do qual este controlador depende:
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);
}
}
}
O problema ocorre na seguinte linha do módulo do controlador:
this.calBlock = response.data;
O problema é que ISTO está indefinido, portanto calBlock também está indefinido e o jsConsole lança um erro:
TypeError: Não é possível definir a propriedade 'calBlock' de indefinido em shift-calendar-controller.js?cdv=28:14
Sou relativamente novo em JavaScript, Angular e TypeScript, então estou tendo dificuldade em entender por que "this" está indefinido. Acho que é porque está dentro de uma função.
Preciso de uma forma de atribuir o response.data (um array JSON de uma chamada $http) à propriedade calBlock da classe TypeScript do meu controlador. Alguém pode me ajudar a entender por que this está indefinido dentro da função de resposta e como posso acessá-lo?
Obrigado
EDITAR: SOLUÇÃO BASEADA na resposta de tymeJV
aqui está a chamada calBlock reescrita:
calSvc.getMonthBlock(12, 2015, 1, this.deptId)
.then((response) => {
//promise fullfilled (regardless of outcome)
this.calBlock = response.data;
},
(error) => {
//handle errors
alert(error);
}
);
Resposta #1
Porque o contexto de this é perdido no callback. Use funções arrow em TypeScript para preservar o contexto!
calSvc.getMonthBlock(12, 2015, 1, this.deptId).then((response) => {
})
