返回可观察值之前,角图未循环

时间:2019-05-02 12:50:36

标签: angular typescript

我正在检索http响应,我需要将json主体提取到数组中。我已成功检索,但主要问题是遍历map中返回的数据。返回可观察值之前不会循环。

在服务器类中,我得到json响应并注意到for循环,它跳转到return res;而没有循环。同样,我在forLoop中打印的所有内容均无效。

  getServers() {
    return this.http.get('https://udemy-ng-http-56bbb.firebaseio.com/data.json')
      .pipe(map
      (res => {
        servers1: any;
        servers1 = res;
        for (const server of servers1) {
          server.name = 'FETCH_' + server.name;
        }
        return res;
      }));
  }

onGet()中,我也尝试在订阅时循环播放。仍然无法正常工作

  onGet() {
    this.serverService.getServers().subscribe(
       (response) => {
         for (this.server of response) {
           this.server.name = 'FETCH_' + this.server.name;
           console.log( this.server.name.json());
         }
       },
       (error) => console.log(error)
    );
  }

我希望这个forloop可以像下面那样在没有pipe的情况下工作。我正在将RxJS 6+..pip(map)..一起使用。在没有管道的情况下使用rxjs-compat时可以正常工作

  getServers() {
    return this.http.get('https://udemy-ng-http-56bbb.firebaseio.com/data.json').map
      (res => {
        this.servers1 = res;
        for (const server of this.servers1) {
          server.name = 'FETCH_' + server.name;
        }
        return res;
      });
  }

这是输出。

-LdlacC74PPS93h9HzQc: Array(2)
0:
capacity: 10
id: 1108
name: "Testserver"
__proto__: Object
1:
capacity: 100
id: 953
name: "Liveserver"
__proto__: Object
length: 2
__proto__: Array(0)
-LdnUvw_idV440wn3uIA: Array(2)
0:
capacity: 10
id: 6006
name: "Testserver"
__proto__: Object
1:
capacity: 100
id: 4260
name: "Liveserver"
__proto__: Object
length: 2
__proto__: Array(0)
__proto__: Object

名称应为FETCH_ Testserver,而不仅仅是Testserver

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

getServers() {
    return this.http.get('https://udemy-ng-http-56bbb.firebaseio.com/data.json')
      .pipe(map
      (res => this.transformationMethod(res)));
  }

transformationMethod(res){ 
  Object.keys(res.data).forEach(resKey => { 
     const obj = res.data[resKey]; 
     obj.forEach(data => { 
        data.name = 'Fetch_' + data.name; 
     }) 
   }) 
  return res; 
}

对于像这样的数据

data = {
    "data": {
      "-LdlacC74PPS93h9HzQc": [{
        "capacity": 10,
        "id": 1108,
        "name": "Testserver"
      }, {
        "capacity": 100,
        "id": 953,
        "name": "Liveserver"
      }],
      "-LdnUvw_idV440wn3uIA": [{
        "capacity": 10,
        "id": 6006,
        "name": "Testserver"
      }, {
        "capacity": 100,
        "id": 4260,
        "name": "Liveserver"
      }]
    }
  };

A sample demo