I'm currently working on a unique custom select component that retrieves data from a service call initiated by its parent component. In cases where the initial service call fails, I need to implement a retry function within the select component itself. However, when the function is called, the expected this
context is not being passed as intended:
Here's an example of my parent component setup:
<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>
The object fields.bank
in the parentComponent.ts file contains properties, including the retry function:
bank: {
...
retryFunction: this.banksService.queryAll, //<-- banksService is a private variable defined in the constructor of the parent component
},
Within custom-select.component.html:
<div class="select__error">
<span>
<a class="select__retry-link" (click)="retry()">retry</a>.
</span>
</div>
In custom-select.component.ts:
retry(event?: Event): void {
if (event) { event.preventDefault(); }
if (typeof (this.retryFunction) === 'function') {
this.retryFunction();
}
}
service.ts details below:
constructor(
public httpClient: HttpClient, //<-- Changed from private to public but still encountering issues.
) { }
public queryAll(): Observable<Bank[]> {
return this //<-- Referring to CustomSelectComponent instead of the service itself causes errors.
.httpClient
.get<BankResponse[]>(environment.apiUrls.banks)
.pipe(map(result => {
return this.mapToBankModels(result);
}));
}
My main concern is how to correctly call the service without facing mismatches with the this
context?