这是我第一次try 打字脚本和Angular ,我被一个问题困住了.
我用以下方式定义了一个模块控制器(.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);
}
);
}
}
}
以下是该控制器所依赖的服务:
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);
}
}
}
故障发生在控制器模块的以下线路上:
this.calBlock = response.data;
问题是THIS未定义,因此calBlock也未定义,jsConsole会抛出一个错误:
TypeError:无法设置未定义的属性"calBlock"
我对javascript、angular和typescript比较陌生,所以我很难弄清楚为什么"this"是未定义的.我认为这是因为它包含在一个函数中.
我需要一种分配回复的方法.数据(来自$http调用的json数组)到我的控制器的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);
}
);