【问题标题】:Nested http requests with map with rxjs in Angular2在Angular2中使用带有rxjs的地图嵌套http请求
【发布时间】:2017-04-19 14:58:08
【问题描述】:

我是 Rxjs(以及一般的 Angular2)的新手,我无法理解 RxJS 的微妙之处。

我想对 GitLab API 进行两次 REST 调用:

  1. 接收某个用户的所有组(通过 gitlab.com/api/v4/groups)。这会给我一个像这样的 JSON:

    [ { “身份证”:1511397, "name": "某个名字", “parent_id”:1505403, ... }, { “身份证”:1511403, "name": "其他名字", “parent_id”:1505403, ... } ]
  2. 接收每个组的所有项目(通过 gitlab.com/api/v4/groups/:id),为您提供 1 个组的详细版本:

    {
    "id": 1511397,
    "name": "group name",
    "parent_id": 1505403,
    "projects": [
        {
            "id": 3099499,
            "description": "project 1"
        },
        {
            "id": 3099489,
            "description": "Project 2"
        }
    ]
    }

所以基本上我需要遍历第一个请求给出的所有 ID 并提供一组组详细信息:

[
 {
 "id": 1511397,
 "name": "group name",
 "parent_id": 1505403,
 "projects": [
     {
         "id": 3099499,
         "description": "project 1"
     },
     {
         "id": 3099489,
         "description": "Project 2"
     }
 ]
 },
 {
 "id": 1194997,
 "name": "a second group name",
 "parent_id": 152393,
 "projects": [
     {
         "id": 9423423,
         "description": "project 3"
     },
     {
         "id": 2394238,
         "description": "Project 4"
     }
 ]
 }
]

如何做到这一点?我已经尝试过一些类似于 switchMap、concatMap 和 MergeMap 的方法,但我永远无法让它工作......

【问题讨论】:

    标签: angular gitlab rxjs angular2-observables


    【解决方案1】:

    你可以这样做

    getGroups() {
      return this.http.get('gitlab.com/api/v4/groups')
        .map(res => res.json()) // convert to object[]
        .map(res => res.map(g => g.id)) // get all id
        .mergeMap(gid => {
          let gs = [];
          gid.forEach(id => {
            let req = this.http.get(`gitlab.com/api/v4/groups/${id}`);
            gs.push(req);
          });
          return Observable.forkJoin(gs);
        })
        .map(res => { // we have array of Response Object
            return res.map(x => x.json()); // Array.map not Observable map operator.
        });
    }
    
    getGroups().subscribe(res => console.log(res))
    

    【讨论】:

      【解决方案2】:

      类似的东西。您需要将静态 Observable.of 替换为 $http observables。

      Rx.Observable.of([{userId:1}, {userId:2}])
      .switchMap(ids => Rx.Observable.of(...ids))
      .mergeMap(userId => {
       return Rx.Observable.of([
         {userId:userId, name:'project1'},
         {userId:userId, name:'project2'}
       ]);
      })
      .subscribe(x=>console.log(x));
      
      1. Rx.Observable.of([{userId:1}, {userId:2}]) - 就像 http 调用给你的用户数组 2 .switchMap(ids => Rx.Observable.of(...ids)) - 为每个用户创建一个单独的 observable
      2. .mergeMap 为每个用户 observable 调用 $http 来获取项目。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-26
        • 2018-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-13
        相关资源
        最近更新 更多