得到正确的#34;这个"使用动态函数调用的内部服务

时间:2017-11-09 17:06:04

标签: angular typescript this

在我的应用程序中,我认为这是一个聪明的想法,我将在3个不同的函数中重用代码,这些函数需要相同的参数,但使用它访问不同的API端点。

我尝试将一个变量分配给服务中的正确端点函数,然后调用该变量,但显然this在通过引用调用函数时不再引用服务对象?我不确定,但我得到的错误基本上是this在服务中未定义。

我的组件内的功能:

  submitRefurb() {
    let endpoint = this.refurbService.addRefurb;
    if (this.updating) {
      endpoint = this.refurbService.updateRefurb;
    } else if (this.refurb.id) {
      endpoint = this.refurbService.verifyRefurb;
    }
    this.loading = true;
    endpoint(this.refurb).subscribe( //This is where we have the problem
      (result) => {
        console.log(result);
      },
      (error) => {
        this.loading = false;
      }
    );
  }

Refurbs服务:

@Injectable()
export class RefurbsService {
  constructor(public httpClient: HttpClient, public sharedService: SharedService) {}
  // `this` is undefined if called like it was above
  addRefurb(refurbData, context = [this.sharedService.sectionSelected]) {
    const body = { refurb: refurbData, context};
    return this.httpClient.post(window.location.protocol + '//' + window.location.hostname  + '/refurbs/add', body);
  }

  verifyRefurb(refurbData, context = [this.sharedService.sectionSelected]) {
    const body = { refurb: refurbData, context};
    return this.httpClient.post(window.location.protocol + '//' + window.location.hostname  + '/refurbs/verify', body);
  }

  updateRefurb(refurbData, context = [this.sharedService.sectionSelected]) {
    const body = { refurb: refurbData, context};
    return this.httpClient.post(window.location.protocol + '//' + window.location.hostname  + '/refurbs/update', body);
  }
}

现在,我终于通过简单地将endpoint变量指定为字符串来实现它,而不是直接将其分配给函数,如下所示:

let endpoint = 'addRefurb'; ... this.refurbService[endpoint](this.refurb)

但是我还没有完全理解出了什么问题,有人可以解释一下有什么区别吗?有没有比我最终做的更好的方式来处理它?<​​/ p>

2 个答案:

答案 0 :(得分:2)

您可以使用scene.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent me)方法:

bind

答案 1 :(得分:1)

使用箭头功能:

let endpoint = (refurbData) => this.refurbService.addRefurb(refurbData);

或者只是存储observable而不是端点:

let obs = this.refurbService.addRefurb(this.refurb);
...
obs.subscribe(...)