【发布时间】:2020-03-02 03:04:22
【问题描述】:
我想搜索从 API 获取的用户列表。我首先初始化列表,然后我希望能够过滤列表的用户名。我已经用异步 observables 构建了逻辑。但在我的第二个功能内。 searchList() 我在this.userList => Function of type void can't be assigned to type Observable<any> 和我的控制台中收到错误:
_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<any>,但this.filterUsers(this.searchTerm)的类型为void,因为函数体中没有返回任何内容。 -
我并没有真正得到我必须返回的内容,因为我已经在
filterUsers()中返回了结果
标签: javascript angular typescript ionic-framework rxjs