【问题标题】:In Typeahead, unable to subscribe to service to get data to bind to typeahead search在 Typeahead 中,无法订阅服务以获取绑定到 typeahead 搜索的数据
【发布时间】:2019-02-18 13:12:36
【问题描述】:

我正在使用 ngbootstrap 预输入 (https://ng-bootstrap.github.io/#/components/typeahead/examples#http)

根据提到的示例,我们需要将 observable 返回到 [ngbTypeahead]="search"

我们期待来自 API 的以下结果

{ "data": { "groupNames": [ "group level one", "group level two", "group level one", "group level two" ] } }

从这个返回结果中,我们需要通过包含单词进行过滤。

search = (text$: Observable<string>) => text$.pipe( debounceTime(300), distinctUntilChanged(), map((term) => term.length < 1 ? [] : this.productService.getGroups().subscribe((response) => { if (response && response.data) { return response.data.groupNames.filter((response) => response.toLowerCase().indexOf(term.toLowerCase()) > -1); } }, ), ), )

问题:

我如何将以下结果返回为可观察到 typahead 属性

return response.data.groupNames.filter((response) =&gt; response.toLowerCase().indexOf(term.toLowerCase()) &gt; -1);

(注意 - 我们从服务中获取全部数据,我们根据用户类型从结果中过滤结果)

【问题讨论】:

    标签: angular angular6 typeahead bootstrap-typeahead


    【解决方案1】:

    从订阅回调返回几乎没有意义。您可以尝试用 switchMap 替换 subscribe 并从流中返回事件,而不是尝试在订阅中返回事件。我想工作示例看起来像:

    search = (text$: Observable<string>) =>
        text$.pipe(
          debounceTime(300),
          distinctUntilChanged(),
          switchMap((term) => term.length < 1 ? of([]) :
            this.productService.getGroups().pipe(
              filter((response) => response && response.data)
              map((response) => response.data.groupNames.filter((response) => response.toLowerCase().indexOf(term.toLowerCase()) > -1))
            )
          ),
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 2021-11-18
      • 2018-03-01
      • 2021-09-02
      相关资源
      最近更新 更多