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?