Angularjs 构造函数中更新的变量在Typescript中的类中可用吗?
在我的代码中,有一条消息是使用AngularJS$emit发送的,在构造函数中的$on函数中接收的。当我调试时,它会经常转到下面的行,这样我就知道它正在工作:Angularjs 构造函数中更新的变量在Typescript中的类中可用吗?,angularjs,typescript,Angularjs,Typescript,在我的代码中,有一条消息是使用AngularJS$emit发送的,在构造函数中的$on函数中接收的。当我调试时,它会经常转到下面的行,这样我就知道它正在工作: this.lastSuccessResponse = +new Date(); 但是,当我检查控制台时,每60秒打印一次的消息总是打印last:undefined 任何人都能看到问题所在,以及为什么console.log似乎没有为lastSuccessResponse记录新的号码 class ConnectService {
this.lastSuccessResponse = +new Date();
但是,当我检查控制台时,每60秒打印一次的消息总是打印last:undefined
任何人都能看到问题所在,以及为什么console.log似乎没有为lastSuccessResponse
记录新的号码
class ConnectService
{
lastSuccessResponse: number;
static $inject = [
"$interval",
"$rootScope"
];
constructor(
public $http: ng.IHttpService,
public $interval,
public $rootScope
) {
$rootScope.$on('rootScope:success-response', function () {
this.lastSuccessResponse = +new Date();
});
}
checkConnection = () => {
var self = this;
this.$interval(function () {
let intDate = +new Date();
console.log("date: " + intDate);
console.log("last: " + self.lastSuccessResponse);
}, 60 * 1000);
}
}
您在
checkConnection
中正确地防止了丢失此
,但在构造函数中没有
此代码
$rootScope.$on('rootScope:success-response', function () {
this.lastSuccessResponse = +new Date();
});
应该是这样(将函数
更改为箭头函数以在回调中保留此
):
另请参见TypeScript常见问题解答中的条目:
$rootScope.$on('rootScope:success-response', () => {
this.lastSuccessResponse = +new Date();
});