在ngFor中合并两个数组

时间:2017-11-07 21:26:41

标签: arrays angular merge

我从服务中得到两个数组:

handleProjectLoaded(project){

    this.projectService.getCodesByType( "Structure" ).subscribe( response => {

        this.structures = response;
    });

    this.projectService.getCodesByType( "Direction" ).subscribe( response => {

        this.lines = response;
    });
}

一个阵列在结构中,第二个我在线上。我将它们分别用于html和ngFor展示。

<div class="div-width-button3">
    <select #lineSelect class="custom-select custom-select-project" style="flex-basis:49%" (change)="addDirection(directionSelect.value); directionSelect.selectedIndex = 0;">
        <option selected disabled value="">Add a direction</option>
        <option *ngFor="let direction of directions" [value]=direction.id
            [selected]="direction.id==directionSelect.value">{{direction.name}}</option>
    </select> 
    <select #structureSelect class="custom-select custom-select-project"  style="flex-basis:49%"
        (change)="addStructure(structureSelect.value); structureSelect.selectedIndex = 0;">
        <option selected disabled value="">Add a structure</option>
        <option *ngFor="let structure of structures" [value]=structure.id
            [selected]="structure.id==structureSelect.value">{{structure.name}}</option>
    </select>
</div>

我需要解决方案将这两个数组显示为一个带有一个ngFor。有没有办法合并它们?

2 个答案:

答案 0 :(得分:3)

我没有测试它,但为什么不使用concat?

<option *ngFor="let line of lines.concat(structures)" [value]="line.id">{{ line.name }}</option>

答案 1 :(得分:1)

handleProjectLoaded(project){

  this.projectService.getCodesByType( "Structure" )
    .concat(this.projectService.getCodesByType( "Line" ))
    .subscribe(response => {
      this.structuresAndLines = response;
    });

}

===编辑===

实际上我改变了主意,因为我认为前面例子中的structuresAndLines是一个二维数组。所以请试试这个:

handleProjectLoaded(project){

  Observable.zip(
    this.projectService.getCodesByType( "Structure" ),
    this.projectService.getCodesByType( "Line" ),
    (structures, lines) => structures.concat(lines),
  )
  .subscribe(response => {
    this.structuresAndLines = response;
  });

}