如何使用 angular 跳过过时的回复?

How to skip outdated responses with angular?

在 angular(不是 angularjs)中取消对服务器的过时请求的最佳模式是什么?

  1. 用户发起搜索请求 #1
  2. 用户发起搜索请求#2
  3. 服务器 returns 搜索响应 #2
  4. 服务器 returns 搜索响应 #1

因此,我们遇到了 UI 中的请求和响应不匹配的错误。

例如,Typeahead 具有部分有用的 typeahead-wait-ms 属性,但我正在寻找更通用的解决方案。

是否有取消请求的简单模式?或者将请求 ID 与最新的进行比较?

PS:我们正在使用 HttpClient,因此我们的调用在内部看起来类似于以下 GET 实现:

protected get<T>(url: string, request: any = {}, options: any = {}): Observable<T> {
    request.rnd = (new Date()).getTime();

    return this.http.get<T>(url, {headers: this.buildHeaders(options),
        responseType: 'json', params: request})
    .pipe(
            catchError((err: HttpErrorResponse) => {
                ... error Handlig
            })
        );
}

如果您使用的是响应式表单,并且您的字符串源是表单控件,通常它看起来像这样:

searchSource = new FormControl('')
search(searchString: string) {
  // returns observable of search logic
}
ngOnInit() {
  this.searchSource.valueChanges.pipe(
    switchMap(toSearch => this.search(toSearch)) // switchmap automatically cancels old requests on new values
  ).subscribe(results => {
    // always results for LAST emitted value
  })  
}

关键是在您感兴趣的值的来源处使用 switchMap,因此您只查看最新值的结果。