角度形式控制最后可观察到的变化

问题描述 投票:1回答:1

我正在构建一个自动完成功能,它正在查询后端的建议,并且只想在用户键入角度5表单控件时获得最后一次查询。目前我的代码看起来像

 this.newVendorForm.get('address').valueChanges.pipe(delay(3000)).subscribe(
  address => {
    this.geocodeApi.getAddressSuggestions(address)
      .subscribe(
        response => {
          console.log('address suggestions');
          console.log(response);
          this.addressSuggestions = response;
        },
        error => {
          console.log('error getting address suggestion');
          console.log(error);
        }
      )
  }
);

这可行,但它会在3000毫秒后查询每个键入的字母。例如,'test'将在3000 ms后查询['t','te','tes','test']。如何在3000毫秒延迟后从valueChanges中取出最后一次更改(即'test'),然后进行订阅?谢谢你的帮助

angular typescript autocomplete rxjs angular-observable
1个回答
3
投票

你想要的是debounceTimeswitchMap的混合物。

this.newVendorForm.get('address').valueChanges.pipe(
  debounceTime(3000),
  switchMap(address => this.geocodeApi.getAddressSuggestions(address).pipe(
    catchError(err => {
      console.error(err);
      return of();
    })
  )),
  filter(Boolean),
).subscribe(response => this.addressSuggestions = response);
  • debounceTime使得如果在3秒内彼此有两个valueChanges排放,则只使用最后一个。这与delay不同,switchMap将在制作3秒后发出所有变化。
  • getAddressSuggestions采用内部可观察对象,例如http请求,并将可观察流更改为它 - 即您现在订阅了switchMap可观察流。如果有东西发射到getAddressSuggestions,它将取消之前的观察。结果是,如果之前进行的catchError呼叫在新的呼叫开始之前尚未完成,则前一个呼叫将被取消。
  • .catchgetAddressSuggestions的可调运算符版本)用于catchError observable而不是valueChanges。否则,如果API出错,则valueChanges observable将完成。使用filter可以在不完成valueChanges observable的情况下处理错误。
  • of()用于仅发出具有值的响应。如果出现错误,将不会发出.subscribe。这只是解决这种情况的一种方法。

最后你可能想要避免手册.unsubscribe,因为你将不得不| async。相反,您可以尝试依赖模板中的qazxswpoi管道,该管道将为您处理订阅。

© www.soinside.com 2019 - 2024. All rights reserved.