javascript - 类型为 void 的函数不能分配给类型 Observable<any>

标签 javascript angular typescript ionic-framework rxjs

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

_co.searchChanged is not a function

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

我的代码:

服务.ts

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

页面.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
  }

页面.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>  

最佳答案

Function of type void can't be assigned to type Observable.

错误消息说 userList 期望分配一个 observable 但 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;
    })
  );
}

关于javascript - 类型为 void 的函数不能分配给类型 Observable<any>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58716442/

相关文章:

angular - 尽管在异步管道订阅的管道中,Observable 似乎仍然存在

angular - 如何在父组件中动态加载 Angular 4中的组件

javascript - 将数据从模型提取到变量

javascript - 如何使用 gruntfile 将 Node js 应用程序部署到 heroku

javascript - typescript 中可能具有未定义值的逻辑运算符

javascript - 在wordpress中联系表格7如何在正文中包含javascript src

javascript - 如何在 Cypress.io 中多次运行测试

javascript - 这不会访问 http 响应对象 :property does not exist on type Object

javascript - 如果找到数组中的元素,如何将其添加到数组中?

javascript - 发布 TypeScript React 组件时有关 TS 类型的问题