首页 > 解决方案 > 在 Angular2+ 中使用带有 Kedno UI Gid 的 switchMap

问题描述

我将 Kendo UI 用于带有数据绑定的 Angular Grid。我有两种服务:一种是从过滤器组件向网格组件发出搜索事件,另一种是(基于 BehaviorSubject)调用 API。

我使用的与 Grid 进行数据绑定的方式是基于 Kendo 示例。问题是当用户在过滤器输入中输入文本时如何使用 switchMap 来取消 API 请求。我知道 switchMap 运算符,但我不知道如何在基于 Kendo UI Grid 的服务中使用它。我尝试了很多方法都没有成功,我没有更多的想法。我的代码如下:

Grid 组件中使用的 API 服务方法

public query(state: any): void {  
    this.getItems(state)
        .subscribe(x =>   
            super.next(x));  
}  

private getItems(state: any): Observable<GridDataResult>{  
    let page = state.skip / state.take + 1;
    let queryStr =         
    `page=` + page + 
    `&size=` + state.take + 
    `&sortColumn=` + state.sortColumn + 
    `&sortDirection=` + state.sortDirection;

    return this.http  
        .get(`${this.BASE_URL}FindItemsComplex?${queryStr}`)  
        .pipe(
            map(response => (<GridDataResult>{
                data: response['data'],
                total: response['length']
            }))
        );  
}    

网格组件方法

ngOnInit() {
   this.subscription = this.searchService.searchEvent.
   debounceTime(400).
   subscribe((searchModel: ItemsFilter) => 
     {
       this.state = searchModel;   
       this.state.skip = 0;   
       this.state.take = 15;
       this.service.query(this.state);  
     }
   );    
 }

我应该在哪里以及如何使用 switchMap?谢谢您的帮助。

编辑

用于发出事件的过滤器组件方法

HTML

<input kendoTextBox [(ngModel)]="itemsFilter.textSearch" (ngModelChange)="onSearch()" [ngClass]="'form-control'" />

TS

onSearch() {
   this.searchService.Search(this.itemsFilter);
}

搜索服务

export class ItemsSearchService {
   constructor() {
       this.searchEvent = new EventEmitter();
   }

   Search(query :ItemsFilter) {
       this.searchEvent.emit(query);
   }

   searchEvent: EventEmitter<ItemsFilter>;
}

标签: angulartypescriptrxjskendo-ui-angular2switchmap

解决方案


当用户在过滤器输入(如“switchMap”)中键入文本时,函数“debounceTime”也可以取消 API 请求。你已经使用了'debounceTime',所以你不需要再次使用'switchMap'。


推荐阅读