Angular - 自动完成搜索无法正常工作

Angular - Autocomplete Search doesn't work properly

我在使用 Angular 实现带有自动完成功能的搜索框时遇到了问题。在我的搜索框中,自动完成显示了完整的联系人列表,尽管从 console.log 我可以看到过滤器工作正常。我认为这与 observables 相关的一些问题有关,但我不确定要更改的位置和内容,我已经被困了一段时间。

ngOnInit() {
  this.contactsForm = this.fb.group({
    userInput: null
  }); 
this.filteredContacts = this.contactsForm
  .get('userInput')
  .valueChanges
  .pipe(
    startWith(''),
    debounceTime(300),
    switchMap(value => {
      if (value !== '') {
        return this.search(value);
      } else {
        return of(null);
      }
    })
  );
}

这是我的搜索功能,从 console.log 我可以看到过滤器工作正常,但在 ngOnInit 方法中获取整个联系人列表,因此在自动完成中我获取所有姓名。

search(value: string): Observable<Contact[]> {
    return this.apiService.getContacts().pipe(
      tap((contacts: Contact[]) => {
        contacts = contacts
          .map(contact => new Contact(contact._id, contact.type, 
contact.name, contact.address))
      .filter(contact => contact.name.includes(value))
    console.log({contacts})
    return contacts;
  })
);
}

此处提供完整代码:https://github.com/nicolagheza/gestionalino-frontend/tree/develop

感谢您的宝贵时间。 尼古拉

在您的 search 方法中将 tap 替换为 map

然而,

tap simply allows you to do stuff with emitted values but doesn't change them in the process. map 确实如此。