Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.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 角度2。失去这一承诺的范围_Javascript_Angular_Promise - Fatal编程技术网

Javascript 角度2。失去这一承诺的范围

Javascript 角度2。失去这一承诺的范围,javascript,angular,promise,Javascript,Angular,Promise,我觉得我错过了一些东西。我有一个获取数据的服务。我将其转换为承诺,然后尝试以单独的方法处理数据 一旦它击中了方法,我就失去了访问我的对象的能力,而我通常会从这里访问这些对象。如果我将addJobsToTree中的所有代码保留在then块中,那么它就可以正常工作。我还可以从组件中的任何其他位置访问它。我肯定我在做一些愚蠢的事情,但我想不出来 ngOnInit(){ this._scheduleDataService.getSavedScheduleData(this.buildDateSt

我觉得我错过了一些东西。我有一个获取数据的服务。我将其转换为承诺,然后尝试以单独的方法处理数据

一旦它击中了方法,我就失去了访问我的对象的能力,而我通常会从这里访问这些对象。如果我将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);
    }
}

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

您可以使用
bind
方法:

ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
      .toPromise()
      .then(this.addToJobsTree.bind(this); // <-----
}
可能重复的
ngOnInit(){
this._scheduleDataService.getSavedScheduleData(this.buildDateStringFromCalendar(),1004)
      .toPromise()
      .then((data) => { // <-----
        this.addToJobsTree(data);
      });
}