如何使用 API 获得预先输入的建议

How to get typeahead suggestions with API

尝试获取名称作为 ng-typeahead 建议并尝试了以下代码但无法获取自动建议。这是我的代码。

fnPopulateEntity1Lovs() {
  this.http
    .get("https://reqres.in/api/products/", {})
    .subscribe((res) => {
      this.testData = res;
    });
}

search: OperatorFunction < string, readonly string[] > = (text$: Observable < string > ) =>
  text$.pipe(
    debounceTime(200),
    distinctUntilChanged(),
    map(term => term.length < 2 ? [] :
      this.testData.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
  )

演示:StackBlitz
你能告诉我如何获得预输入选项吗?

HTML

<input id="typeahead-http" type="text" 
  class="form-control mx-sm-3" 
  [class.is-invalid]="searchFailed" 
  [(ngModel)]="model" 
  [ngbTypeahead]="search" 
  [inputFormatter]="formatter"
  [resultFormatter]="formatter"
  placeholder="Product search" />

服务:创建服务产品服务

@Injectable(
  {
    providedIn: 'root'
  }
)
export class ProductService {
  constructor(private http: HttpClient) {}

  search(term: string) {
    if (term === '') {
      return of([]);
    }

    return this.http.get<any>(PRODUCTS_URL).pipe(
        map(response => response.data), //since the response is wrapped in a data object
        tap(res => console.log({res}))
      );
  }
}

现在像这样在组件中调用搜索

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

使用结果格式化程序

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

演示:StackBlitz Project