Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 构造函数中更新的变量在Typescript中的类中可用吗?_Angularjs_Typescript - Fatal编程技术网

Angularjs 构造函数中更新的变量在Typescript中的类中可用吗?

Angularjs 构造函数中更新的变量在Typescript中的类中可用吗?,angularjs,typescript,Angularjs,Typescript,在我的代码中,有一条消息是使用AngularJS$emit发送的,在构造函数中的$on函数中接收的。当我调试时,它会经常转到下面的行,这样我就知道它正在工作: this.lastSuccessResponse = +new Date(); 但是,当我检查控制台时,每60秒打印一次的消息总是打印last:undefined 任何人都能看到问题所在,以及为什么console.log似乎没有为lastSuccessResponse记录新的号码 class ConnectService {

在我的代码中,有一条消息是使用AngularJS$emit发送的,在构造函数中的$on函数中接收的。当我调试时,它会经常转到下面的行,这样我就知道它正在工作:

 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();
    });