ng-bootstrap typeahead:如何处理 Observable<Person[]> 而不是 Observable<string[]>

ng-bootstrap typeahead: how to handle Observable<Person[]> rather than Observable<string[]>

我有一个新手Angular/Typescript问题。

我遵循了 ng-bootstrap typeahead 中定义的 Wikipedia 示例,我决定用提供以下 GET 调用的自定义 REST 服务替换 Wikipedia 调用:

和 returns 匹配姓名的人员列表,其中每个人是:

Person(id:long, name:string, surname:string)

现在从打字稿部分和 angular 部分一切正常,如果我将人员数组映射(...)到 _service 中的名称字符串数组:

但我不想在 _service 和 returns 人员列表中以这种方式映射,以允许用户单击下拉列表中的结果,然后显示该人员的详细信息没有后续调用。

所以目前在我的打字稿组件中,模型是:

model: Observable<Person[]>;

搜索部分如下:

search = (text$: Observable<string>) =>
        text$.pipe(
            debounceTime(300),
            distinctUntilChanged(),
            tap(() => this.searching = true),
            switchMap(term =>
                this._service.search(term).pipe(
                    tap(() => this.searchFailed = false),
                    catchError(e => {
                        this.searchFailed = true;
                        return of([]);
                    }))
            ),
            tap(() => this.searching = false),
            merge(this.hideSearchingWhenUnsubscribed)
        )

而 html 部分是:

 <div class="input-group input-group-lg" id="person-search">
        <input name="name" id="typeahead-http" type="text" class="form-control" [class.is-invalid]="searchFailed" (selectItem)="selectedItem($event)" [(ngModel)]="model" [ngbTypeahead]="search" placeholder="Search a person"/>
        <span class="input-group-btn">
            <button class="btn btn-primary btn-lg" type="button">
              <i class="text-muted fa fa-search"></i>
            </button>
        </span>
  <div>

我怎样才能在下拉列表中只显示姓名并允许用户单击姓名并向他显示相应的人?

你需要一个 resultFormatter 来显示名称,但你还需要 inputFormatter 来在你选择一个值时只显示名称,否则它会在 [object Object]输入字段。这些都是提前输入的。

所以在你的 ts 中,标记你想要在结果和输入中显示名称:

formatter = (x: { name: string }) => x.name;

您将像这样在模板中使用它们:

<input ... [resultFormatter]="formatter" [inputFormatter]="formatter"/>

您的 model 仍将包含整个对象。