【问题标题】:How to skip outdated responses with angular?如何用角度跳过过时的响应?
【发布时间】:2020-02-28 02:53:13
【问题描述】:

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

  1. 用户发起搜索请求 #1
  2. 用户发起搜索请求#2
  3. 服务器返回搜索响应 #2
  4. 服务器返回搜索响应 #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
            })
        );
}

【问题讨论】:

    标签: angular angular-httpclient angular-http-interceptors


    【解决方案1】:

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

    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,以便您只查看最新值的结果。

    【讨论】:

    • 谢谢,看起来很相关。确认后接受
    • 这通常是这样,您只需要获取您想要关闭的值到您的流中。反应式表单很好,因为它们已经为您将表单值放入流中(并且您可以根据需要使用任何相关的运算符,如 debounce),但如果您不能,例如按钮单击是触发器,您可以创建您自己的主题并在用户点击时触发它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2021-07-03
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多