可观察对象:取消新订阅呼叫上的先前的HTTP请求

V S*_*S X 5 httprequest subscribe observable rxjs angular

我正在为我的项目开发搜索功能。用户在搜索栏上键入任何内容后;搜索文本发生任何更改时,我都会将文本发送到后端进行验证并收到响应(文本错误或无错误):

this.searchBar.on('change', () => {

    http.post('api_link', {searchText: 
       this.serachBar.searchText}).subscribe(resp => {
            this.resp = resp['Result'];
       });
    })
Run Code Online (Sandbox Code Playgroud)

现在,当用户不断在搜索栏中键入内容时,后端会收到多个验证响应。但是,在进行任何新更改时,只有最新的订阅才有效,并且以前对api的任何调用都是无用的。

有什么办法可以使用订阅取消对api的任何新调用上的先前订阅?

注意:似乎可以等待所有响应,但是我还将在搜索栏下方显示响应(直到那时显示一个加载程序)。因此,我希望加载程序一直加载直到最新的响应可用,而不是在各种响应状态之间转换。

Jos*_*mer 28

我会使用一个主题来保持一切反应。在您的模板 html 中侦听更改事件并向主题发出新值。

 <searchBar (change)="search$.next($event.target.value)" />
Run Code Online (Sandbox Code Playgroud)

然后在您的组件中:

  this.subscription = this.search$.pipe(
     debounceTime(800), 
     distinctUntilChanged(),
     switchMap(searchText=>http.post('api_link', {searchText})
    }).subscribe(response=>{
       this.response = response.
    });
Run Code Online (Sandbox Code Playgroud)

如果通过主题发出新值,switchMap 将取消任何尚未完成的 HTTP 请求。你可以玩 debouneTime 来看看什么适合你。最后,确保您在 ngOnDestroy 中取消订阅您的主题,这将防止任何内存链接并保持一切正常和性能。:

ngOnDestroy(){
   this.subscription. unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)

Suresh的答案有一个distinctUntilChanged()这是一个极好的补充解决方案。我正在添加它,但想归功于他在下面的回答。这是一个好处,因为如果我搜索egg请求。但是后来我添加了一个s鸡蛋的结尾并在去抖动完成之前改变了主意,另一个重复的 HTTP 帖子将不会搜索鸡蛋。


Sur*_*iya 10

您需要使用 debounceTime 和 switchMap 运算符。

this.searchBar.on('change', () => {

    of(this.serachBar.searchText).pipe(
       debounceTime(400),
       distinctUntilChanged(),
       switchMap((text)=> {
          return http.post('api_link', {searchText: text}).map(resp => {
            return resp['Result'];
          });
        });
    ).subscribe(response=> console.log(response));

});
Run Code Online (Sandbox Code Playgroud)