首页 > 解决方案 > 需要帮助将加载指示器添加到订阅 Rxjs 主题的搜索栏

问题描述

我有一个搜索栏字段,我使用服务来运行我的搜索功能,如下所示:

// signup.ts

ngOnInit() {
  this.filteredOptions$ = this.searchService.search(this.searchTerm$);
}

搜索词是主题的地方:

<input type="text" placeholder="Your Business Name" aria-label="Number" matInput (keyup)="searchTerm$.next($event.target.value)"
        [matAutocomplete]="auto">

我想在搜索功能启动和完成时显示加载指示器,但问题是这是一项服务(使用可注入)。这是我的搜索功能:

// searchservice.ts
  public search(terms: Observable<string>): Observable<ABN> {
    return terms.pipe(
      debounceTime(400),
      distinctUntilChanged(),
      switchMap(term => this.searchEntries(term)),
    );
  }

然后我在我的模板上订阅这个。如何将其作为服务保存在单独的文件中,但仍更新组件上的局部变量(isLoading)?

标签: angulartypescriptrxjsrxjs6

解决方案


只需向您的组件添加一个加载变量,然后在您的组件中管道您的源和目标可观察对象:

ngOnInit() {
  this.filteredOptions$ = this.searchService.search(
      this.searchTerm$.pipe(tap(() => this.loading = true)
  ).pipe(finalize(() => this.loading = false));
}

这让组件中的加载标志保持关注,我同意它所属的位置。


推荐阅读