typescript 如何外包subscribe()方法中的匿名函数逻辑?

odopli94  于 2023-01-06  发布在  TypeScript
关注(0)|答案(1)|浏览(101)

考虑如下代码块:

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)
      }
    );
  }

我尝试将subscribe()内部的逻辑外包给一个单独的方法,如下所示:

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)
  }

这里的问题是:我无法将包含subscribe()fetchUsers()方法的参数传递给subscribe()上正在调用的handleSubscribedResponse函数作用域。fetchUsers函数参数count未传递给此作用域。我们如何从上述fetchUsers方法传递参数?
我尝试使用bind()apply()如下,但它是没有用的:

// 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))

我怎样才能得到订阅处理函数的参数值?

nqwrtyyt

nqwrtyyt1#

最好的解决方案是,您应该拥有一个具有以下功能的服务
第一个月

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

在您的组件中,您可以像这样
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)
}

相关问题