为什么“;这个“;在具有http promise的typescript模块中未定义
why "this" is undefined in typescript module with http promise
这是我的第一次打字和角度尝试,我遇到了一个问题。
我有一个模块控制器定义如下(.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"在shift-calendar-controller.js?cdv=28:14
我对javascript、angular和typescript相对陌生,所以我很难弄清楚为什么"this"是未定义的。我认为这是因为它包含在一个函数中。
我需要一种方法来将reponse.data(来自$http调用的json数组)分配给我的控制器的typescript类的calBlock属性。有人能帮我理解为什么这个在响应函数中未定义,以及我如何访问它吗?
感谢
编辑:基于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) => {
})
相关文章:
- Typescript模块没有导出的成员-react
- Visual Studio 2015 Update 2-'中的TypeScript模块;要求'未定义
- 可以't在不提供文件扩展名的情况下导入TypeScript模块
- Typescript 0.9.1.1模块被拆分为几个.ts文件
- Typescript模块和systemjs.从内联脚本实例化类
- 通过 RequireJS 从 javascript 调用 TypeScript 模块
- jspm / jQuery / TypeScript - 模块“jquery”没有默认导出
- 来自 TypeScript 模块的 JavaScript IIFE 中的默认参数的目的是什么?
- 用requireJS加载一些typescript模块
- 运行时未定义Typescript模块
- 为什么“;这个“;在具有http promise的typescript模块中未定义
- 使用typescript模块进行Browserify -什么是最佳设计实践?
- 从typescript模块中注册Knockout.js组件视图模型
- Typescript模块放到单个JS文件中
- 需要帮助来理解Angular 2/Typescript模块在Prime NG中的声明
- 如何在NodeJS中公开TypeScript模块
- 无法使用——out将typescript模块(.ts)文件连接到单个输出(.js)中
- Typescript模块工厂模式
- 引用嵌套的TypeScript模块
- Typescript模块,需要外部node_modules