Reputation: 3118
I am having an issue using Angular Material Table with DataSource.
This is my HTML template:
<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>
This is my service:
getFilms(): Observable<FilmModel[]> {
return this.httpClient.get<FilmModel[]>(`'http://localhost/api/getFilms');
}
This is my component trying to use DataSource from Angular Material:
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() {}
}
And this is the model entity:
export interface FilmModel {
created: string;
director: string;
edited: string;
episode_id: number;
opening_crawl: string;
producer: string;
release_date: string;
title: string;
url: string;
}
The error that I have every time it hit the getFilm service is:
Error trying to diff '[object Object]'. Only arrays and iterables are allowed
This is how looks the returned response from the API call:
{
count: 7,
next: null,
previous: null,
results: [{...}]
}
My guess will be that it is trying to apply the data source to an object while it is expecting an array so I can iterate tough the response.
How can I amend my code to read only results
Array from the response data?
Upvotes: 0
Views: 1204
Reputation: 222722
You need to access the results from the data object, Change your service method as,
return this.http.get<Project[]>(environment.apiRoot + 'projects/GetProjects').map(data => data.results);
Upvotes: 1