如何通过forkJoin保持价值

时间:2018-11-28 13:32:23

标签: javascript angular typescript rxjs6

我有一个场景,我必须获得2个http调用的结果,并将它们的组合结果数组传递给我要实例化的类。这是代码:

export class VideoListComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource: VideoListDataSource;
  constructor( private http: HttpProxyService, private videoService: VideoService ) { }
  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['Video Name', 'Author', 'Category Name', 'Highest Quality Format', 'Release Date', 'Options'];

  ngOnInit() {
    let observables = [this.videoService.getInitialData('movie-authors'), this.videoService.getInitialData('movie-categories')];
    forkJoin(observables).subscribe(res => {
      this.dataSource = new VideoListDataSource(this.paginator, this.sort, res);
      console.log(this.dataSource);
    })
  }

}

现在,在console.log上,我可以根据需要看到this.dataSource中的值,但是在html模板上使用它时,它表示this.dataSource是未定义的。

有帮助吗?我在这里想念东西吗?

使用HTML标记进行编辑

<div class="mat-elevation-z8">
  <table mat-table class="full-width-table" [dataSource]="dataSource" matSort aria-label="Elements">
    <!-- Id Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let row">{{row.id}}</td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
      <td mat-cell *matCellDef="let row">{{row.name}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

  <mat-paginator #paginator
      [length]="dataSource.data.length"
      [pageIndex]="0"
      [pageSize]="50"
      [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>
</div>

1 个答案:

答案 0 :(得分:0)

如下修改您的代码:

namespace CTB_APP.Controllers.API.Delete
{
[RoutePrefix("api/test/")]
public class TestController : ApiController
{
    [Route("name/{param}")]
    public string Get(string param)
    {
    return param + 1;
    }

   [Route("age/{param}")]
   public int Get(int param)
   {
      return param + 1;
   }
 }
}

为什么我的代码不起作用:

  

您正尝试使用未初始化的数据源填充表数据。数据源从服务中获取价值。由于视图是在调用服务之前初始化的,而 dataSource 的时间是未定义的,因此会引发错误。