在Typeahead中,无法订阅服务以获取要绑定到预先搜索的数据

问题描述 投票:0回答:1

我正在使用ngbootstrap typeahead(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) => response.toLowerCase().indexOf(term.toLowerCase()) > -1);

(注意 - 我们从服务中获取整个数据,从结果中我们按照用户类型进行过滤结果)

angular angular6 typeahead bootstrap-typeahead
1个回答
0
投票

从订阅回调返回几乎没有任何意义。您可以尝试使用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))
        )
      ),
    )
© www.soinside.com 2019 - 2024. All rights reserved.