【问题标题】:Transform an observable to an array将 observable 转换为数组
【发布时间】:2019-03-24 19:17:37
【问题描述】:

我想将一个 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]

【问题讨论】:

  • 数组在哪里以及如何使用?我在这里看不到任何地方。
  • @theMayer 我想迭代 this.HygroS3 =val[0].HygroS3 以获得许多行..
  • 您是否要在模板中显示此内容?模板在哪里?
  • @chupicupa 只想搞定这个,val 的第一行总是['date','HygroS3','HygroS4','HygroS5']

标签: javascript angular firebase observable


【解决方案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>

【讨论】:

    【解决方案2】:

    嗯..我不确定我是否过度简化了这种情况,或者我不完全理解你的问题,但假设返回的 observable 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);
      });
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2016-06-02
      • 2014-10-24
      • 2020-12-01
      • 2017-09-24
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      相关资源
      最近更新 更多