Angular6 - Utilizing service calls as references in child components

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?

Answer №1

Utilize the queryAll method as an arrow function

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

Alternatively, you can specify the value of this using Function.prototype.call()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The property you are trying to set is undefined and cannot

When I attempt to set a property 'error' that is undefined, I receive a TypeError. The problematic line of code looks like this: this.error = error.code; This issue arises in an Angular Reactive Form while making a call to a web service. Below i ...

Having trouble establishing a connection with the C# Controller when processing the frontend request

Having trouble implementing the Search by siteId functionality using typescript and C#. The issue arises when trying to connect to the C# controller from the frontend request. The parameter I need to pass is siteId. Below is the code snippet: HTML: ...

The parameter type cannot be assigned to an array type of 'IAulasAdicionais[]'

I am facing a problem in my application that I need help solving. The issue lies within my code, and I have included some prints of the error below: Mock data: "AulasAdicionais": [ { "Periodo": "1", "Hora ...

The module '@angular/compiler' is missing and cannot be located at this time

Upon running the command npm install -g @angular/cli and attempting to run my application, I encountered an error message in the terminal stating that it could not find the module '@angular/compiler'. How can I include the compiler in my package. ...

angular 2 loading elements synchronously

Within my local or session storage, there exists a JWT token containing the userId information. When a user refreshes the page on a route such as test.com/route2 the app.components.ts initiates an http request to fetch the roles. constructor( p ...

Using *ngIf and *ngFor in Angular to switch between divs depending on their index values

Is there a way to toggle between two divs based on the index value using *ngIf in Angular? I have attempted to do so by toggling boolean values of true and false, but my current approach is not working. Here is what I have tried so far: <div *ngFor=&qu ...

Developing typeScript code that can be easily translated and optimized for various web browsers

Can TypeScript alleviate the worry of having to use code such as this (especially when considering browsers like IE that may not support indexOf)? arrValues.indexOf('Sam') > -1 Does the transpiling process in TypeScript generate JavaScript c ...

The headerStyle does not have any impact on the header component in React-Native

Currently diving into React-Native with Typescript and working on a project. Encountered a bug where the header color isn't changing as expected. Any help or insight would be greatly appreciated! -Viggo index.tsx import React, { Component } from & ...

Is it possible to make *ngIf in Angular run just one time?

I am facing a minor issue - I need to implement roles validation in my Angular application. The structure of the application consists of pages, each containing multiple components. User privileges are assigned at the component level, making it necessary to ...

Create a separate helper function to extract browser logs using Protractor's afterEach

My main objective is to create a helper function that extracts the browser.manage().logs() data. I am working towards this goal by incorporating the functionality of browser.manage().logs() within the afterEach method in my test script. I have noticed tha ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

MongoMemoryServer - Dealing with Unexpected Errors

Currently, I am conducting tests on a typescript express-mongoose app using jest, supertest, and mongo-memory-server. Interestingly, all the tests are passing successfully, but an error keeps popping up in every test involving mongo-memory-server. It see ...

"What is the most effective way to utilize and integrate the `setValue` function from react-hook-form within a custom react hook

Struggling to pass setValue to a react hook? In my custom react hook, I need to set values in a form using react-hook-form's setValue. Yet, after migrating from v6 to v7, I'm having trouble figuring out the proper typing for this. This is how t ...

NgZone is no longer functioning properly

Seemingly out of the blue, my NgZone functionality has ceased to work. I'm currently in the process of developing an application using Ionic, Angular, and Firebase. An error is being thrown: Unhandled Promise rejection: Missing Command Error ; Zon ...

Please eliminate the notification stating "The baseHref option is deprecated, instead use the baseHref option directly in the browser builder."

After updating my project to Angular version 11, I encountered an error when trying to run it: "Option baseHref is deprecated, use baseHref option in the browser builder itself". I attempted to add baseHref: "/certs/" in angular.json, but the error persis ...

Utilizing TypeScript interfaces to infer React child props

How can I infer the props of the first child element and enforce them in TypeScript? I've been struggling with generics and haven't been able to get the type inference to work. I want to securely pass component props from a wrapper to the first ...

When making a GET request using Angular HttpClient, an error message stating "No overload matches this call" may

One issue I am facing is with a GET method in my backend. When sending a request body as input, I receive a list of results in return. However, the problem arises in my frontend: search(cat: Cat): Observable<Cat[]> { return this.httpClient.ge ...

Angular Dependency Injection: Individual instances of each service are provided for every module usage

Within my application, there is a module called "FileUpload". The upload service included is "UploadService", which receives a service injection with the interface "RequestService." I also have two other modules: FileManager1 and FileManager2. Each file m ...

AmCharts 4: defining the grid interval

I am currently working on creating a polar chart to showcase Satellite data. https://i.sstatic.net/DNUZ1.jpg However, I am facing a challenge with setting the grid size to be displayed in increments of 45 degrees. Despite trying various amcharts 4 functi ...

Encountered a TypeError when using Angular 2 with ng-bootstrap and NgbTabset: Uncaught (in promise) error due to inability to read property 'templateRef'

I am attempting to use NgTabset but encountering an error that reads TypeError: Cannot read property 'templateRef' of undefined. Strangely, when I replace the ng-template with the template tag, everything works smoothly. Can anyone help me identi ...