Angular 6自动建议搜索框

时间:2018-12-21 02:41:35

标签: angular typescript rxjs

我正在按照本教程https://medium.com/@nacimidjakirene/angular-search-autosuggest-with-observables-6f42987f80e6进行操作,我想以角度6进行操作。

如何将其转换为与angular 6兼容的代码?

ngOnInit() {
    this.queryField.valueChanges
    .debounceTime(200)
    .distinctUntilChanged()
    .switchMap((query) =>  this._searchService.search(query))
    .subscribe( result => { if (result.status === 400) { return; } else {   this.results = result.json().artists.items; }
  });
  }
}

我自己进行了转换,但是在 this.logframe.searchEmployee(term).subscribe()

上出错
ngOnInit() {
    this.registerationForm.valueChanges
    .pipe(
      debounceTime(200),
      distinctUntilChanged(),
      switchMap((term) => this.logframe.searchEmployee(term).subscribe()),
    );
  }

如果您对此有其他选择,请告诉我:)

编辑: 解决了我的问题:)

我只需要通过获取特定的formcontrol来调整Fan Cheung代码,然后还添加catcherror,以使它在404在null之后无法完成

ngOnInit() {
    this.registerationForm.get('name').valueChanges
    .pipe(
      debounceTime(200),
      distinctUntilChanged(),
      switchMap((term) => this.logframe.searchEmployee(term).pipe(catchError(err => of('null')))),
    ).subscribe(
      val => console.log(val)
    );
  }

2 个答案:

答案 0 :(得分:0)

订阅返回SubscriptionswitchMap无法使用 如果this.logframe.searchEmployee(term)返回Observable,请尝试以下代码

ngOnInit() {
    this.registerationForm.valueChanges
    .pipe(
      debounceTime(200),
      distinctUntilChanged(),
      switchMap((term) => this.logframe.searchEmployee(term)),
    );
  }

答案 1 :(得分:0)

解决了我的问题:)

我只需要通过获取特定的formcontrol来调整Fan Cheung代码,然后还添加catcherror,以使它在404在null之后无法完成

ngOnInit() {
    this.registerationForm.get('name').valueChanges
    .pipe(
      debounceTime(200),
      distinctUntilChanged(),
      switchMap((term) => this.logframe.searchEmployee(term).pipe(catchError(err => of('null')))),
    ).subscribe(
      val => console.log(val)
    );
  }