无法访问组件内的功能 - Angular2

时间:2017-02-08 05:42:56

标签: javascript angular

无法想出这个。我有一个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);
}

1 个答案:

答案 0 :(得分:0)

问题可以是范围,当使用promises或Observable时,在回调函数中检索的范围(成功,错误,最终,完成)是声明它的类。我曾经在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中的代码可能会提供一些更有用的信息,但同样的问题可能是如果箭头函数被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中的绑定功能并检查终端中的错误。

相关问题