我使用Angular Material Table with DataSource时出现问题。
这是我的HTML模板:
<div>
<mat-table [dataSource]="dataSource">
<ng-container matColumnDef="created">
<mat-header-cell *matHeaderCellDef> Created </mat-header-cell>
<mat-cell *matCellDef="let film"> {{film.created}} </mat-cell>
</ng-container>
<ng-container matColumnDef="director">
<mat-header-cell *matHeaderCellDef> Director </mat-header-cell>
<mat-cell *matCellDef="let film"> {{film.director}} </mat-cell>
</ng-container>
<ng-container matColumnDef="edited">
<mat-header-cell *matHeaderCellDef> Edited </mat-header-cell>
<mat-cell *matCellDef="let film"> {{film.edited}} </mat-cell>
</ng-container>
<ng-container matColumnDef="episode_id">
<mat-header-cell *matHeaderCellDef> Episode ID</mat-header-cell>
<mat-cell *matCellDef="let film"> {{film.episode_id}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row;columns: displayedColumns;"></mat-row>
</mat-table>
这是我的服务:
getFilms(): Observable<FilmModel[]> {
return this.httpClient.get<FilmModel[]>(`'http://localhost/api/getFilms');
}
这是我尝试使用Angular Material的DataSource的组件:
import { Component } from '@angular/core';
import { StarWarsService } from '../star-wars.service';
import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs/Observable';
import { FilmModel } from './film.model';
@Component({
selector: 'app-films',
templateUrl: './films.component.html',
styleUrls: ['./films.component.css']
})
export class FilmsComponent {
dataSource = new FilmDataSource(this.swService);
displayedColumns = ['created', 'director', 'edited', 'episode_id'];
constructor(private swService: StarWarsService) { }
}
export class FilmDataSource extends DataSource<any> {
constructor(private swService: StarWarsService) {
super();
}
connect(): Observable<FilmModel[]> {
return this.swService.getFilms()
}
disconnect() {}
}
这是模型实体:
export interface FilmModel {
created: string;
director: string;
edited: string;
episode_id: number;
opening_crawl: string;
producer: string;
release_date: string;
title: string;
url: string;
}
每次点击getFilm服务时出现的错误都是:
Error trying to diff '[object Object]'. Only arrays and iterables are allowed
这是查看API调用返回的响应的方式:
{
count: 7,
next: null,
previous: null,
results: [{...}]
}
我的猜测是它正在尝试将数据源应用于对象,而期望一个数组,这样我就可以对响应进行迭代。
如何将代码修改为只读取响应数据中的results
数组?
答案 0 :(得分:1)
您需要访问数据对象的结果,将服务方法更改为
return this.http.get<Project[]>(environment.apiRoot + 'projects/GetProjects').map(data => data.results);