【问题标题】:Angular6 - Passing service call as reference to child componentAngular6 - 传递服务调用作为对子组件的引用
【发布时间】:2018-08-29 06:37:13
【问题描述】:

我正在开发一个自定义选择组件,该组件从其父组件进行的服务调用中接收数据。如果该给定调用因任何原因失败,我需要将重试函数传递给选择(服务调用本身)。该函数被调用,但是 this 没有按预期传递:

我的父组件:

<div class="form-group row mb-4">
    <div class="col-md-12 col-12">
      <custom-select [field]="fields.bank" [formControlName]="fields.bank.controlName" [errors]="submitted ? formControls.bank.errors : null">
      </custom-select>
    </div>
 </div>

fields.bank 是在 parentComponent.ts 中定义的类型化对象,它传递一些属性,包括重试功能:

bank: {
   ...
   retryFunction: this.banksService.queryAll, //<-- banksService is a private variable defined in parentComponent's constructor
},

自定义-select.component.html

<div class="select__error">
  <span>
     <a class="select__retry-link" (click)="retry()">retry</a>.
  </span>
</div>

custom-select.component.ts

retry(event?: Event): void {
    if (event) { event.preventDefault(); }
    if (typeof (this.retryFunction) === 'function') {
      this.retryFunction();
    }
  }

service.ts

constructor(
    public httpClient: HttpClient, //<-- it was initially private, but public also doesn't work.
  ) { }

public queryAll(): Observable<Bank[]> {
  return this //<-- this is referring to CustomSelectComponent, not to the service itself. Throws error.
    .httpClient
    .get<BankResponse[]>(environment.apiUrls.banks)
    .pipe(map(result => {
      return this.mapToBankModels(result);
    }));
}

我的问题是:如何在没有this 不匹配的情况下正确调用服务?

【问题讨论】:

标签: angular typescript angular6


【解决方案1】:

你可以让queryAllarrow function

public queryAll = (): Observable<Bank[]> => {
  return this
    .httpClient
    .get<BankResponse[]>(environment.apiUrls.banks)
    .pipe(map(result => {
      return this.mapToBankModels(result);
    }));
}

或者您可以使用Function.prototype.call() 指定this 的值

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    相关资源
    最近更新 更多