【问题标题】:Function of type void can't be assigned to type Observable<any>void 类型的函数不能分配给 Observable<any> 类型
【发布时间】:2020-03-02 03:04:22
【问题描述】:

我想搜索从 API 获取的用户列表。我首先初始化列表,然后我希望能够过滤列表的用户名。我已经用异步 observables 构建了逻辑。但在我的第二个功能内。 searchList() 我在this.userList => Function of type void can't be assigned to type Observable&lt;any&gt; 和我的控制台中收到错误:

_co.searchChanged 不是函数

我真的不知道为什么会出错。

我的代码:

service.ts

// get the user list from the api
getList(offset = 0): Observable<any> {
    return this.http.get(`${this.url}/users?offset=${offset}&limit=10`)
  }

page.ts

 public searchTerm: string = "";
 userList: Observable<any>;

constructor(private userService: UserService) {}

 ngOnInit() {

    this.getAllUsers();   // intialize the userList which should be searched
 }

  // function to map the users
  getAllUsers() { 
    this.userList = this.userService.getList(this.offset) 
    .pipe(map(response => response.results));
  }

  // filter the users for username
  filterUsers(searchTerm) {
    this.userList.subscribe(res => {
      const result = res.filter(user => {
        return user.username.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
      });
      return result;
    });
  }

  searchList() {
    this.userList = this.filterUsers(this.searchTerm);  // here I get the error
  }

page.html

<ion-searchbar mode="ios" class="items-searchbar" animated mode="ios" [(ngModel)]="searchTerm" (ionChange)="searchList()" placeholder="Filter by name..."></ion-searchbar>
...
<ion-list>
    <ion-item  lines="none" *ngFor="let user of (userList | async); let i = index">
      </ion-item>
  </ion-list>  

【问题讨论】:

  • 就像错误所说:userList 期望 Observable&lt;any&gt;,但 this.filterUsers(this.searchTerm) 的类型为 void,因为函数体中没有返回任何内容。
  • 我并没有真正得到我必须返回的内容,因为我已经在 filterUsers() 中返回了结果

标签: javascript angular typescript ionic-framework rxjs


【解决方案1】:

void 类型的函数不能分配给 Observable 类型。

错误消息说userList 期望分配一个可观察对象,但filterUsers() 没有返回任何内容,因此返回并分配了void

修改fitlerUsers() 函数以返回一个可观察对象。我正在使用map() 运算符来转换结果。

filterUsers(searchTerm) {
  return this.userList.pipe(
    map(res => {
      const result = res.filter(user => {
        return user.username.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
      });
      return result;
    })
  );
}

【讨论】:

  • 感谢修复了我的错误。但是,奇怪的是搜索功能不起作用:/
  • @ColinRagnarök - 我不明白为什么它不起作用。如果您可以在StackBlitz 或类似网站上重现此代码,我会看看。
  • 我的问题是我的字符串在删除搜索栏中的搜索词时没有重置。因此,如果我没有任何结果并且我想进行新的搜索,我必须重新加载应用程序才能再次查看我的用户列表。
  • 搜索功能有效,但清理搜索栏输入时无法重置字符串
  • @ColinRagnarök - 更改字符串时会给出不同的结果吗?如果您可以共享代码,我会看一下,这将是一个简单的修复。如果没有更多信息,我无话可说。
猜你喜欢
  • 2021-09-23
  • 2019-03-27
  • 2018-08-14
  • 2017-08-12
  • 2021-12-10
  • 1970-01-01
  • 2018-08-30
  • 2020-05-28
  • 2018-03-09
相关资源
最近更新 更多