繁体   English   中英

无法访问组件内的函数-Angular2

[英]Cannot access function within component - Angular2

无法弄清楚这一点。 我有一个从服务器获取结果的OnInit函数。 结果,我希望运行一个angular2抱怨“ this.secondsToTime不是函数”的函数。

这是我的代码:

    ngOnInit() {
    this.user = this._authService.user;
    this._globalService.getPrintTimer().subscribe(
        suc => {
            this.secondsToTime(suc.response);
        },
        err => {
            console.log("Could not load timer");
        }
    );
}

secondsToTime(time) {
    console.log("secondsToTime");
    setTimeout(function () {
        time--;
        time = Math.round(time);
        var hours = Math.floor(time / (60 * 60));

        var divisor_for_minutes = time % (60 * 60);
        var minutes = Math.floor(divisor_for_minutes / 60);

        var divisor_for_seconds = divisor_for_minutes % 60;
        var seconds = Math.ceil(divisor_for_seconds);

        this.countDown = minutes + ":" + seconds;
    }, 1000);
}

问题可能是范围,当使用promise或Observables时,在回调函数中检索到的范围(成功,错误,最后,完成)属于声明它的类。 我以前在ES5,ES6中编写代码时遇到此错误,并且自从我开始使用箭头函数声明函数/方法以来就没有遇到过此错误,因为箭头函数是块作用域的。

为了解决您的问题,代码中的此修改应起作用:

 ngOnInit() {
    this.user = this._authService.user;
    this._globalService.getPrintTimer().subscribe(
        suc => {
            this.secondsToTime(suc.response);
        }.bind(this),
        err => {
            console.log("Could not load timer");
        }.bind(this)
    );
}

我创建了plnkr来复制错误,但是由于您使用的是箭头功能,因此无法使用您提供的代码复制该错误,globalService中的代码可能会提供一些更有用的信息,但是如果使用arrow功能可以复制相同的问题函数被function(){}代替,修改后的代码:

 ngOnInit() {
    this.user = this._authService.user;
    this._globalService.getPrintTimer().subscribe(
        function(suc) {
            this.secondsToTime(suc.response);
        }.bind(this),
        function(err) {
            console.log("Could not load timer");
        }.bind(this)
    );
}

如果删除bind()方法,则会收到错误,this.secondsToTime未定义。 以下是指向plnkr的链接: https ://plnkr.co/edit/vMbkdG4F5CbQxfyXGIHQ?p = preview。

您可以尝试删除plnkr中的bind函数,并在终端中检查错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM