【问题标题】:How to put on hold all other httpclient API request until main API request is finished and resume other hold API request?如何暂停所有其他 httpclient API 请求,直到主 API 请求完成并恢复其他暂停 API 请求?
【发布时间】:2020-02-11 19:47:45
【问题描述】:

我将在用户登录并进入主布局页面后加载一些主要数据。有多个 API 请求用于加载主要数据。所以我想暂停其他 API 请求,直到主 api 请求完成

主要的 API 请求也是按顺序完成的。

我已经添加了 HttpInterceptor 用于添加一些标题和所有内容。

解释现在发生的事情。

  • 我有 _layout 组件,它有标签,所以所有其他页面都将加载到这个组件中。
  • _layout 正在加载 ngOnInit 上的一些主要数据,这些数据将在进一步的 API 请求中使用

问题是 在刷新页面时,其他 API 请求不会等待完成在 _layout 组件中启动的主要 API 请求的请求。

我们无法确定在 _layout 组件初始化后将调用多少 API 请求,因为所有路由都在此完成。

【问题讨论】:

  • 检查concatMap
  • 嵌套订阅对我不起作用,因为在刷新页面时我无法假设在主 API 之前完成了多少 api 请求。我有主要 api 的列表。我不确定 resolve 对此有何帮助。
  • 向我们展示代码,您尝试过什么?您在哪里遇到问题?
  • 没有任何代码可以解决这个问题
  • 你可以为http实现队列,参考这个stackoverflow.com/questions/48021728/…

标签: angular typescript api angular6


【解决方案1】:

我认为为此你应该使用 rxjs 的 .flatMap() 运算符。该操作符一般用于顺序调用api。

请查看以下链接以获取更多信息: http://reactivex.io/documentation/operators/flatmap.html https://stackoverflow.com/a/40666072/9766269

【讨论】:

    【解决方案2】:

    在您的 _layout 组件模板中,创建一个 ng-container 标签并将所有子组件标签放入 ng-container。现在您可以在 ng-container 标记上设置一个 ngIf,以在主 api 尚未给出响应的情况下不渲染子组件。这样子组件 Api 就不会被触发。希望这可以帮助。

    【讨论】:

    • 如果对您有用,请接受答案。谢谢。
    【解决方案3】:

    试试这个:

    this.http.get(mainApiUrl).pipe(
        switchMap(
            mainApiResponse => {
            // mainApiResponse has result from main api
            return forkJoin(
                [
                    this.http.get(otherApiUrl1),
                    this.http.get(otherApiUrl2)
                ]
            ).pipe(map(otherResponsesArr => [mainApiResponse, ...otherResponsesArr]))
        })
    ).subscribe(responseArr => {
            mainResponse = responseArr[0];
            otherResponse1 = responseArr[1];
            otherResponse2 = responseArr[2];
        });
    

    说明

    调用主 api 并在获得响应时,我们使用 switchmap 运算符检索第一个 api 调用的输出,取消订阅并将结果传递给使用 forkjoin 调用下一组 api(实际用例可能会有所不同)。

    【讨论】:

    • 感谢您的努力,请您再看一遍问题,我已经更新了。
    • 阅读下面给出的我的新答案。
    【解决方案4】:
    this.http.get(url).subscribe(res => {
             // Main Api is Called here
            }, error => {
              console.log(error);
            }, () => {
              console.log('When api Request is Complated');
                // Rest of the API Called here When Main Api In Completed.
            }
          );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2016-09-08
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多