为 PrimeNG 表格式化 Angular 可观察数据

问题描述

我有一个基于 Angular.io 教程的项目,包括“Hero”接口和数据,以及使用 HTTPClient 的“HeroService”。

我能够使用模板中的标准 HTML 获取数据并显示它,但在使用 PrimeNG 表时无法使用他们网页中的示例。所以我有模板所需的数据,但我不确定如何将其正确传递给 PrimeNG。我希望在不改变 HeroSerice 的工作方式的情况下做到这一点。

我通常对 Observables、Promises 和相关技术感到困惑,所以很难进一步描述。我已阅读 Using PrimeNG with Observables (rxjs) in Angular 4,但未解决我的问题。

英雄界面:

export interface Hero {
  id: number;
  name: string;
}

InMemoryDataService:

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const heroes = [
      { id: 11,name: 'Dr Nice' },{ id: 12,name: 'Narco' },{ id: 13,name: 'Bombasto' },{ id: 14,name: 'Celeritas' },{ id: 15,name: 'Magneta' },{ id: 16,name: 'RubberMan' },{ id: 17,name: 'Dynama' },{ id: 18,name: 'Dr IQ' },{ id: 19,name: 'Magma' },{ id: 20,name: 'Tornado' }
    ];
    return {heroes};
  }

来自 HeroService 的方法

  /** GET heroes from the server */
  getHeroes(): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        catchError(this.handleError<Hero[]>('getHeroes',[]))
      );
  }

我的 TreeTableComponent:(在我把它缩小成一个表格之前命名的)

export class TreeTableComponent implements OnInit {

  heroes: Hero[] = [];
  

  constructor(private heroService : HeroService) { }

  ngOnInit() {
    this.getHeroes();
  }
  
  getHeroes(): void {
    this.heroService.getHeroes().pipe(tap(heros => console.log(heros)))
    .subscribe((heroes: Hero[]) => {
      this.heroes = heroes as Hero[];
    }
      )};

所以,问题:

这有效:

  <ul class="heroes">
    <li *ngFor="let hero of heroes">
      <a routerLink="/detail/{{hero.id}}">
        <span class="badge">{{hero.id}}</span> {{hero.name}}
      </a>
    </li>
  </ul>

但这不会:

<p-table [value]="heroes"| async>
    <ng-template pTemplate="header">
        <tr>
            <th>id</th>
            <th>name</th>        
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-hero>
        <tr>
            <td>{{heroes.id}}</td>
            <td>{{heroes.name}}</td>
        </tr>
    </ng-template>
  </p-table>[enter image description here][1]

我得到的错误是:

TS2339:类型“Hero[]”上不存在属性“id”。

TS2339:“Hero[]”类型上不存在属性“name”。

![1]:https://i.stack.imgur.com/EJ06E.png

解决方法

您使用了错误的变量名称。

<ng-template pTemplate="body" let-hero>

在上面的行中,您将变量命名为“hero”以访问“heroes”数组的各个元素。所以,属性应该这样调用:

<td>{{hero.id}}</td>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...