我有两个很好用的观测仪器:
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
...
merge(this.sort.sortChange, this.paginator.page)
.pipe(
startWith({}),
switchMap(() => {
return this.getUsers(this.sort.active, this.sort.direction, this.paginator.pageIndex);
}),
map(userApi => {
这使得
getUsers
在更新排序或分页时要调用的服务方法。
现在,我还希望在键入搜索词时调用此服务方法:
@ViewChild(String) searchTerm: string;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
...
merge(this.searchTerm.length, this.sort.sortChange, this.paginator.page)
.pipe(
startWith({}),
switchMap(() => {
return this.getUsers(this.searchTerm, this.sort.active, this.sort.direction, this.paginator.pageIndex);
}),
map(userApi => {
使用以下模板标记:
<mat-form-field>
<input matInput #searchTerm (keyup)="search($event.target.value)" placeholder="User name" autocomplete="off">
</mat-form-field>
但是服务方法永远不会被调用,即使在页面加载时也是如此。
我的想法是让搜索项成为可观察的,并且让这个可观察的被
merge
方法。这样,我只有一个方法调用
获取用户
服务方法。
我也试过这个陈述(没有
.length
)但它没有改变任何东西:
merge(this.searchTerm, this.sort.sortChange, this.paginator.page)
更新:我现在正在尝试这条线:
@ViewChild('searchTerm') searchTerm: ElementRef;
merge(this.searchTerm.nativeElement.changes, this.sort.sortChange, this.paginator.page)
这个
search
事件处理程序不更新fine
searchTerm
成员变量:
search(searchTerm: string) {
this.searchTerm.nativeElement.value = searchTerm.trim().toLowerCase();
if (this.paginator) {
this.paginator.firstPage();
}
}
我想我可以得到输入字段元素的值来调用服务方法:
return this.getUsers(this.searchTerm.nativeElement.value, this.sort.active, this.sort.direction, this.paginator.pageIndex);
但是
合并
如果它包括
this.searchTerm.nativeElement.changes
如:
merge(this.searchTerm.nativeElement.changes, this.sort.sortChange, this.paginator.page)
如何拥有
检索词
是否观察输入字段的值变化?