我有一个角服务返回的承诺。在我的控制器中,我想将值分配给控制器的“this”对象。在我的Visual Studio编辑器,它认为,“这”将是正确的对象,当我编辑(this.something显示在智能感知),但是当这个运行时,事情是不确定的,因为这是窗口对象。我究竟做错了什么?AngularJS与打字稿承诺-成功此目的是窗口
this.webapi.getSites().success((data: Array<Isite>): void => {
this.something = data; // this becomes the window object so something is undefined.
}).error(function (error: any) {
});
与其他答案不同,它不是未定义的,它被设置为窗口对象。该transpiled代码如下所示:
topnav.prototype.loadSiteInfo = function() {
var _this = this;
this.webapi.getSites().success(function (data) {
_this.something = data;
}).error(function (error) {
});
};
好像它应该工作,我...
你没有做错什么,[这就是如何在JavaScript的作品(http://www.quirksmode.org/js/this.html):)这是一个常见的问题,[这个问题](http://stackoverflow.com/q/24145178/398606)有一个很好的解决方案(使用var self = this;')。 –
[MDN(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)有一个很好的说明也是如此。 –
@SunilD。请注意,OP使用箭头运算符(又名词法分析范围解析运算符)。 Typescript在ES5模式下填充它。 – PSL