将可观察对象转换为数组

时间:2019-03-24 19:17:37

标签: javascript angular firebase observable

我想将一个可观察对象转换为一个表。我可以通过在零行上搜索来显示表格,但是我想浏览所有行以检索所有值。我如何遍历所有行,而不仅仅是获得第一个值? 谢谢

export class DataComponent implements OnInit {

  constructor(private router: Router,public authService: AuthService,public dataService: DatasService) { }

 HygroS3;
 HygroS4;
 HygroS5;
 date;
 datatodisplay2;
 datatodisplay;
 data1 : any [];
 config1: GanttChartConfig;
 elementId1: string;


ngOnInit() {
    this.datatodisplay = this.dataService.getDatas();
    let interestingFields =['date','HygroS3','HygroS4','HygroS5'];
    this.datatodisplay.subscribe(val => {
     this.HygroS3 = val[0].HygroS3; 
     this.HygroS4 = val[0].HygroS4;
     this.HygroS5 = val[0].HygroS5; 
     this.date = val[0].date; 
     this.data1=[['date','HygroS3','HygroS4','HygroS5'],[this.date,this.HygroS3,this.HygroS4,this.HygroS5]]
     console.log(this.data1);
  });

  this.config1 = new GanttChartConfig(new Date (),0,0,0);
  this.elementId1 = 'myGanttChart'; 
}

我得到这个:

Array(2)
0: (4) ["date", "HygroS3", "HygroS4", "HygroS5"]
1: (4) ["24032019170117", 92, 85, 63]

2 个答案:

答案 0 :(得分:1)

嗯..我不确定是否简化了这种情况,或者我不完全理解您的问题,但是假设返回的可观察的val是对象[{.....} ,{.........}],并且您希望返回的格式为[[..],[....]]数组。

ngOnInit() { 

  this.datatodisplay.subscribe(val => {
    const headers = ['date','HygroS3','HygroS4','HygroS5'];
    const res = val.map(row => {
      return [row['date'], row['HygroS3'], row['HygroS4'], row['HygroS5']];
    });
    this.data1 = [headers, ...res]
    console.log(this.data1);
  });

}

这将为您提供问题末尾提到的所需格式的数组,标题位于第一行,其他值位于后续行。

答案 1 :(得分:1)

假设您有一个类似这样的类来表示DatasService.getData()的返回值:

class DataToDisplay {
  date: Date | string;
  HygroS3: number;
  HygroS4: number;
  HygroS5: number;
}

您可以简化ngOnInit的实现,而直接存储对象

data: DataToDisplay[] = [];

ngOnInit() {
  this.dataService.getDatas().subscribe((dataResponse: DataToDisplay[]) => { // assuming dataResponse is an array of your object
    this.data = dataResponse;
  });

  this.config1 = new GanttChartConfig(new Date (),0,0,0);
  this.elementId1 = 'myGanttChart'; 
}

在模板中,您可以像这样干净地引用它:

<table>
    <tr>
        <th>Date</th>
        <th>HygroS3</th>
        <th>HygroS4</th>
        <th>HygroS5</th>
    </tr>
    <tr *ngFor="let item of data">
        <td>{{item.date}}</td>
        <td>{{item.HygroS3}}</td>
        <td>{{item.HygroS4}}</td>
        <td>{{item.HygroS5}}</td>
    </tr>
</table>