如何在Angular 7中处理嵌套的HTTP请求? [英] How to handle nested HTTP requests in Angular 7?

查看:169
本文介绍了如何在Angular 7中处理嵌套的HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用服务,可以从服务器获取数据.收到响应后,我正在使用mapper函数将纯JSON数据映射到所需的模型.对于映射器函数中的某些类类型,我需要从服务器获取一些其他数据.如何强制映射器函数等待第二个请求?

I have a generic service for get data from server. When response received, I'm using a mapper function to map pure JSON data to required model. For some class type in mapper function, I need to get some additional data from server. How can I forcing mapper function wait for second request?

这是我的get函数:

 getChildren(params: ITreeQueryParams): Observable<Optional<T[]>> {
    params.id = isPresent(params.id) ? params.id : 0;
    params.parentId = isPresent(params.parentId) ? params.parentId : 0;
    params.isRoot = isPresent(params.isRoot) ? params.isRoot : false;
    params.additionalId = isPresent(params.additionalId) ? 
    params.additionalId : 0;
    return this.http.get<IListResponse<T>>
(`${this.resourceUrl}/getChildren/${params.id}/${params.parentId}/${params.isRoot}/${params.additionalId}`,
      {
        observe: 'response'
      }).pipe(map((resp) => this.mapResponse(resp,this.model)));
  }

这是我的映射器功能:

 protected mapResponse(resp: any, model: IAsset): void {
    if (resp) {
      this.anotherTreeService.getNodeDetail(resp.id, resp.isRoot).subscribe(res => {
        model.additionalData = {canEdit: res.length > 0 ? true : false};
      });
      if (resp.name) {
        model.title = resp.name;
      }
    }
  }

推荐答案

RxJS中有很多运算符可以实现您想要的.当数据模型本身不包含所有数据并且您需要一个单独的调用以根据第一个结果检索其他数据时,您会看到使用频率很高的例子,如下所示:

There's plenty of operators in RxJS that achieve what you want. What you see used quite often, when a data model in itself does not contain all the data and you need a separate call to retrieve additional data based on the first result is an example like this:

this.myFirstService.getById(id).pipe(
   map(data => jsonToMyModel(data)),
   tap(model => this.data = model),
   switchMap(model => {
      return this.mySecondService.getListById(model.id)
   }),
   tap(secondData => this.data.list = secondData)
).subscribe()

这将改变您要真正实现的目标,因为可以通过使用forkJoin()mergeMap()将所有数据最终存储到Observable返回的一个模型中.这些操作员中的任何一种都在此类情况下使用.

This changes on what you're exactly trying to achieve, as it is possible to have all the data end up in one model returned by the Observable, by using forkJoin() or mergeMap(). Any of these operators have their usage in these type of situations.

希望这会有所帮助.一个更清晰,更直接的示例,需要一个更完整的问题,并提供一些示例,这些示例包含您想要的内容和您尝试过的内容.

Hope this helps. A more clear and direct example of what you want would require a more complete question with some examples of what you want and what you've tried.

这篇关于如何在Angular 7中处理嵌套的HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆