Home > OS >  How to outsource the anonymous function logic present inside subscribe() method?
How to outsource the anonymous function logic present inside subscribe() method?

Time:01-05

Consider a code block like this:

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

      // need to outsource the logic below along with the function argument (count)

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

I tried to outsource the logic inside subscribe() to a separate method as below:

  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 problem here is: I am unable to pass an argument from the method fetchUsers() containing subscribe() to the handleSubscribedResponse function scope which is being called on subscribe(). The fetchUsers function argument count is not passed to this scope. How can we pass the argument from above fetchUsers method?

I tried using bind() & apply() as below but it is of no use:

// 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 I get the argument value in outsourced on subscribe handler function?

CodePudding user response:

A best solution will be like you should have a service having a function like this

userService.ts

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

And in your component you can 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)
}
  • Related