代码之家  ›  专栏  ›  技术社区  ›  Jess

在Angular 6服务中多个map()调用

  •  4
  • Jess  · 技术社区  · 6 年前

    我有一个HTTPGET请求,它返回多个我想变成多个可观测的对象。下面是一个响应示例:

    {
        lookup1: 
        [
          {
            "label": "lookup1 option 1",
            "value": 1
          },
          {
            "label": "lookup1 option 2",
            "value": 2
          }
        ],
        lookup2: 
        [
          {
            "label": "lookup2 option 1",
            "value": 1
          },
          {
            "label": "lookup2 option 2",
            "value": 2
          }
        ]
    }
    

    这是我的服务,有两个观察点:

    this.lookup1 = this.apiService.get('/lookups/')
      .pipe(map(response => response["lookup1"]));
    this.lookup2 = this.apiService.get('/lookups/')
      .pipe(map(response => response["lookup2"]));
    

    如何处理一个HTTP GET请求?

    编辑

    请注意,这样的代码将执行2个HTTP GET请求:

    let lookups = this.apiService.get('/lookups/');
    this.lookup1 = lookups
      .pipe(map(response => response["lookup1"]));
    this.lookup2 = lookups
      .pipe(map(response => response["lookup2"]));
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   madjaoue    6 年前

    方法1

    创建2个主题,在请求解决后将更新这些主题。

    let map1 = new Subject();
    let map2 = new Subject();
    
    this.lookup1 = map1.pipe(map(response => response["lookup1"]));
    this.lookup2 = map2.pipe(map(response => response["lookup2"]));
    
    this.apiService.get('/lookups/').subscribe( response => { 
       map1.next(response);
       map2.next(response);
    })
    

    方法2

    你可以使用 concatMap from 把一条小溪变成另一条。

    this.apiService.get('/lookups/').pipe(
      concatMap( responseJson => from(Object.values(responseJson)))
    ).subscribe( arrayElement=> console.log(arrayElement))
    

    输出:

    // first object emitted : 
    [
      {
        "label": "lookup1 option 1",
        "value": 1
      },
      {
        "label": "lookup1 option 2",
        "value": 2
      }
    ]
    
    // second object emitted :
    
    [
      {
        "label": "lookup2 option 1",
        "value": 1
      },
      {
        "label": "lookup2 option 2",
        "value": 2
      }
    ]
    

    连接图 获取一个可观测的并发射另一个可观测的。

    将不可重复的元素转换为流。你会得到和ITerable项目一样多的排放量。

    推荐文章