简体   繁体   English

Angular2异步嵌套数据

[英]Angular2 async nested data

I have a Angular2 Component displaying some data in a table. 我有一个Angular2组件在表中显示一些数据。

export class DiagnosisComponent {

  headers: Array<String> = ["hello world", "hello world"];
  table: Observable<TableData>;

  constructor(private eventService: EventService) {
    this.table = this.eventService.getDiagnosisEvents();
    this.table.subscribe(console.log.bind(console));
  }

}

And here is the TableData class 这是TableData类

export class TableData {

  content: Array<any>;
  paging: Paging;

  constructor(obj: any) {

    this.paging = {
      size: obj.size,
      totalElements: obj.totalElements,
      currentPage: 1
    };

    this.content = obj.content;

  }

}

export interface Paging {
  size: number;
  totalElements: number;
  currentPage: number;
}

Now I want to bind the table.content Array to a *ngFor with a async pipe. 现在我想将table.content数组绑定到带有异步管道的* ngFor。 My problem is that i need to get the nested data, and not the TableData itself. 我的问题是我需要获取嵌套数据,而不是TableData本身。

<div class="row">

  <vpscout-filter></vpscout-filter>

  <table class="table">
    <thead>
    <tr><th *ngFor="let header of headers">{{header | translate}}</th></tr>
    </thead>
    <tbody>
    <tr *ngFor="let row of table | async ">
      <td>test</td>
    </tr>
    </tbody>
  </table>

</div>

Changing the *ngFor to <tr *ngFor="let row of table.content | async "> does not work. 将* ngFor更改为<tr *ngFor="let row of table.content | async ">不起作用。

I solved a similar problem like this: 我解决了类似这样的问题:

<tr *ngFor="let row of (table | async)?.content ">
      <td>test</td>
</tr>

Since, I'm using immutableJs for my project and converting the observable data to map, the exact solution that worked for me was: 因为,我正在为我的项目使用immutableJs并将可观察数据转换为map,对我有用的确切解决方案是:

<tr *ngFor="let row of (table | async)?.get('content') ">
      <td>test</td>
</tr>

You can create a new field for the content: 您可以为内容创建新字段:

this.table.subscribe((data)=>{
   this.tableContent = data.content
});

and bind that new field to the *ngFor 并将该新字段绑定到*ngFor

 <tbody *ngIf="tableContent">
    <tr *ngFor="let row of tableContent">
      <td>test</td>
    </tr>
 </tbody>

table is of type Observable and not an instance of the TableData class. table的类型为Observable而不是TableData类的实例。 You need to use the Observable's subscribe method to assign an instance of TableData to a variable that is bound to the template/view. 您需要使用Observable的subscribe方法将TableData的实例分配给绑定到模板/视图的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM