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

In Typeahead, unable to subscribe to service to get data to bind to typeahead search

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

根据提到的示例,我们需要 return 可观察到 [ngbTypeahead]="search"

我们期待 API

的结果如下

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

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

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); } }, ), ), )

问题:

我如何 return 低于输入结果 属性

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

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

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

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))
        )
      ),
    )