What is the best way to delegate the anonymous function logic contained within the subscribe() method?

Imagine you have a code block similar to this:

  constructor(private _http: HttpClient) {
    this.fetchUsers(5);
  }
  
  employees: any[] = [];
  
  fetchUsers(count: number) {
    this._http.get(`https://jsonplaceholder.typicode.com/users`).subscribe(

      // the logic below along with the function argument (count) needs to be outsourced

      (users: any) => {
        for(let i=0; i<count; i++) {
          this.employees.push(users[i])
        }
        console.log(this.employees)
      }
    );
  }

An attempt was made to move the logic inside subscribe() to a separate method like so:

  constructor(private _http: HttpClient) {
    this.fetchUsers(5);
  }

  employees: any[] = [];
  
  fetchUsers(count: number) {
    this._http.get(`https://jsonplaceholder.typicode.com/users`).subscribe(this.handleSubscribedResponse);
  }

  handleSubscribedResponse = (users: any) => {


    for(let i=0; i<count; i++) { 
      this.employees.push(users[i])
    }
    console.log(this.employees)
  }

The issue arises when attempting to pass an argument from the fetchUsers() method, which contains subscribe(), to the handleSubscribedResponse function scope that is invoked by subscribe(). The parameter count from the fetchUsers function isn't passed to this scope. How can we achieve passing the argument from the above fetchUsers method?

Attempts were made using bind() and apply() as follows but without success:

// bind()
this._http.get(`https://jsonplaceholder.typicode.com/users`).subscribe(this.handleSubscribedResponse.bind(this, count))

// apply()
this._http.get(`https://jsonplaceholder.typicode.com/users`).subscribe(this.handleSubscribedResponse.apply(this, count))

How can the value of the argument be obtained in the outsourced subscribe handler function?

Answer №1

An effective approach would be to create a service with a function like the following:

userService.ts

fetchUsers(count: number) {
  this._http.get(`https://jsonplaceholder.typicode.com/users`);
}

In your component, you can implement it like this:

app.component.ts

getUsers(userCount: number){
  this.userService.fetchUsers().subscribe((users: any[]) => this.handleSubscribedResponse(users, userCount));
}


handleSubscribedResponse = (users: any, userCount) => {
  for(let i=0; i<count; i++) { 
    this.employees.push(users[i])
  }
  console.log(this.employees)
}

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

Guide to creating jest unit test for an observable variable exclusively utilized in a template resulting in the error "Property 'pipe' of undefined cannot be read"

Seeking help with creating unit tests for an Angular component that utilizes a constructor and observable variable in the HTML template. Below is the code snippet I am having issues with: voice-summary.component.ts export class VoiceSummaryComponent { v ...

`How can TypeScript be used to designate the type of a variable within the useState hook?`

I defined a variable called 'text' and a hook named 'setText'. I'm using them to update the value of a form input field. How can I ensure that 'text' is always of type string? This is what I attempted: interface TextInt ...

How can Angular 4 manage an object containing other objects most effectively?

Who can guide me on the best way to handle a data structure like this: { "1":{ "id":"1", "name":"Facebook", "created_at":"", "updated_at":"", "fields":{ "1":{ "id":"1" ...

What steps should I take to correctly identify the type in this specific situation?

Let's consider the function f, defined as follows: function f<T extends Fields = Fields>(props: Props<T>) { return null; } In this context, T represents a generic type that extends Fields. The concept of Fields is captured by the follow ...

Launching ngx-modal in Angular2 without the need for a button click

As a newcomer to Angular2, I am seeking guidance on how to trigger an alert Modal in the event of a failed login within my code. While most examples I have come across rely on a button click, I am wondering if it is possible to achieve this based on the st ...

What is the process of assigning attribute values conditionally in Angular 2?

I'm currently exploring Angular 2 and facing a challenge with a basic material input tag. I want to dynamically set its value based on a condition. <md-input value="dataSelected ? {{selectedDataName}} : ''"></md-input> I attemp ...

Encountering an issue with importing an enum: An error is triggered stating 'Variable implicitly has type 'any' in certain areas where its type remains undetermined.'

When I define simple enums in the same file, everything works fine. However, exporting/importing them causes numerous compilation errors related to types. It seems like the issue only arises when defining enums in a separate file, pointing towards a proble ...

Enabling Javascript compilation while overlooking typescript errors

Currently, I am working in VS Code with create-react-app using TypeScript. Whenever there are type errors, they show up in the browser and prevent compilation by TypeScript. I am looking for a way to only see these errors in the Google console and termin ...

Error: The specified path in the MEAN stack must be either a string or Buffer

I am currently utilizing Angular 5 on the front-end, Node for back-end operations, and MongoDB as the database. My current challenge involves attempting to save an image to the database, but I keep encountering an error. Determining whether the issue lies ...

JavaScript causing Google custom search to not refresh results when updating search query

I am inputting user IDs into a textbox in my system. Upon submitting the ID, it fetches the name and address of the user and places it in the search box of a GCSE. document.getElementById("gsc-i-id1").setAttribute("value", this.searchqu ...

Harnessing the power of Material-UI's muiThemeable with Typescript

I'm trying to access the current theme colors within a custom React component. The example I'm referencing is from Material UI http://www.material-ui.com/#/customization/themes Despite attempting various approaches, I'm unable to get Typesc ...

The production build failed following the upgrade to ag-grid version 22.1.1

Since version 18, I have been utilizing ag-grid, and I am currently on version 20.0.0. I am now in the process of upgrading to the latest version - 22.1.1. After addressing warnings/errors caused by breaking changes, everything seems to be working fine, ...

Strange actions observed in JavaScript addition operations

In my Angular application, I have the following TypeScript function: countTotal() { this.total = this.num1 + this.num2 } The value of num1 is 110.84 and the value of num2 is 5.54. I determined these values by watching this.num1 and this.num2 in the C ...

Customized interfaces utilizing generic components

Here is my simplified question. interface Identity{ name: string; } Next, we have a generic interface. interface State<T extends Identity>{ [T.name] : StateContainer<T> } Unfortunately, this approach fails and the following error is ...

Leverage rxjs/Typescript to transform an array nested within the data received from an external API

Exploring Typescript/Javascript is a new adventure for me, especially as I delve into the world of rxjs. Here's a snippet of code that I've been working with: return this.http.get<IXenoCantoResponse>(`${this.corsAnywhereUrl}${this.xenoCant ...

Having trouble calling a method from one component to another using its instance

Trying to call a method from one component to another is causing some issues. I have created an instance of the component and tried calling its method, but it doesn't seem to be working as expected. In the code snippet below, you can see that I am try ...

Can you suggest ways to reduce the size of a Docker Image for better optimization?

I have an Angular application running locally on V10. I am attempting to create a Docker image using a Dockerfile. However, during the image creation process, my Docker image size is becoming very large at 1.32GB. Is there any method to decrease its size? ...

Angular Material UI: Nested Table Component

I am dealing with a table that has four static headers and two static columns. The data in the last two columns changes based on certain conditions. I need to convert this table into an Angular Material table. The first table is a standard HTML table. Th ...

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

The Core.js file seems to be missing, but it can be found in the node modules directory. The Meteor client is functioning properly, but there seems to be

I encountered an issue while trying to import the meteor-client.js file. The problem arose when loading ecmascript-runtime-client, which prompted me with an error stating that the core-js npm package could not be found in my node_modules directory. Even af ...