【问题标题】:How to get data from the last http request?如何从最后一个http请求中获取数据?
【发布时间】:2022-06-11 16:26:06
【问题描述】:

我遇到了一个问题,即 http 请求从上次加载的请愿书中获取数据。而不是来自上一个 http 请求。

waterfall network

有什么方法可以停止最后一次通话并获得新的通话吗?

组件

        this.searchForm$.valueChanges
    .pipe(debounceTime(500))
    .subscribe((selectedValue) => {
        this.loading = true;
        this.sExperienceSearch = {...selectedValue.sExperience,...selectedValue.sExperience2,...selectedValue.sExperience3,...selectedValue.sExperience4}
        this.sExperienceSearch.importanceMap = {...selectedValue.sExperience.importanceMap,...selectedValue.sExperience2.importanceMap}
        this.apiService
            .getSearch(this.sExperienceSearch)
            .subscribe((data: any) => {
                this.firstCall = false;
                this.loading = false;
                this.selectedValue = this.sExperienceSearch;
                this.searchData = data;
                this.numVendors = this.searchData.numVendors
                    ? this.searchData.numVendors
                    : 0;
            });
    });
}

服务

 return this.httpClient
        .post<any[]>('/api/advanced-search', body, httpOptions)
        .pipe(
            distinctUntilChanged(),
            map((data) => {
                return data;
            }),
            catchError((error) => {
                return throwError('Something went wrong!');
            })
        );

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    在您的组件中,您使用多个订阅(在每个搜索事件之后),这会导致持续时间较长的 http 调用来提供答案。

    您想要的是在收到新的搜索请求后立即取消对 http-call 的订阅。这样可以确保您只获得最后开始的搜索结果,而不是最后完成的结果。

    你已经在使用 RxJS 管道操作符了;你必须看看 switchMap 操作符来实现你想要的。下面是方向提示。

    组件逻辑:

    this.searchForm$.valueChanges
        .pipe(
          debounceTime(500)
          distinctUntilChanged(),
          switchMap((selectedValue) => {
            this.sExperienceSearch = {...selectedValue.sExperience,...selectedValue.sExperience2,...selectedValue.sExperience3,...selectedValue.sExperience4}
            this.sExperienceSearch.importanceMap = {...selectedValue.sExperience.importanceMap,...selectedValue.sExperience2.importanceMap}
            return this.apiService.getSearch(this.sExperienceSearch)
          })
        ).subscribe(...subscribelogic...)
    
    

    【讨论】:

      猜你喜欢
      • 2014-07-02
      • 2018-04-26
      • 2013-11-01
      • 2021-10-22
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 2018-08-26
      相关资源
      最近更新 更多