Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.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
Javascript 无法访问组件-Angular2内的函数_Javascript_Angular - Fatal编程技术网

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

Javascript 无法访问组件-Angular2内的函数,javascript,angular,Javascript,Angular,我想不出这个。我有一个从服务器获取结果的OnInit函数。因此,我希望运行一个angular2抱怨“this.secondsToTime不是函数”的函数 这是我的密码: ngOnInit() { this.user = this._authService.user; this._globalService.getPrintTimer().subscribe( suc => { this.secondsToTime(suc.re

我想不出这个。我有一个从服务器获取结果的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);
}

当使用承诺或可观察项时,问题可能是范围的问题。在回调函数(success、error、finally、complete)中检索到的范围属于声明它的类。我在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的相同链接:


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

这里可能指的是一个内部调用函数作用域,尝试在调用之前将外部引用保存为var=this,然后使用该.secondsToTime(suc.response);添加“console.log(this);”在您的成功回访中,让我们知道您得到了什么。