我想搜索从 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/