【问题标题】:Angular 2. Losing scope of this in PromiseAngular 2. 在 Promise 中失去 this 的范围
【发布时间】:2016-08-08 04:12:35
【问题描述】:

我觉得我在这里遗漏了一些东西。我有一项服务可以获取一些数据。我将其转换为承诺,然后尝试以单独的方法处理数据。

当它遇到方法时,我失去了访问我通常会从 this.whatever 访问的对象的能力。如果我将 addJobsToTree 中的所有代码留在 then 块中,它就可以正常工作。我还可以从组件中的其他任何地方访问它。我确定我在做一些愚蠢的事情,但无法弄清楚。

ngOnInit(){
    this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
        .toPromise()
        .then(this.addToJobsTree);
}
private addToJobsTree(res){
    for(let xx of res){
        this._sharedService.jobs.push(xx); //Comes back as cannot read _sharedService of null
        console.log(this._sharedService.jobs);
    }
}

【问题讨论】:

标签: javascript angular promise


【解决方案1】:

这是因为你引用了一个函数并且你丢失了函数的上下文。要解决此问题,您需要将函数显式链接到对象。

您可以使用bind 方法之一:

ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
      .toPromise()
      .then(this.addToJobsTree.bind(this); // <-----
}

注意:这是在 TypeScript 中使用 bind 方法的缺点:https://basarat.gitbooks.io/typescript/content/docs/tips/bind.html

或者一个箭头函数来解决这个问题:

ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
      .toPromise()
      .then((data) => { // <-----
        this.addToJobsTree(data);
      });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 2014-12-26
    • 2018-02-10
    • 2017-08-03
    • 1970-01-01
    相关资源
    最近更新 更多