I'm trying to consume an API with Angular 5 but it returns me this error:
" Error trying to diff '[object Object]'. Only arrays and iterables are allowed
at DefaultIterableDiffer.diff".
API Response:
{
"alunos": [
{
"aluno": {
"id": 655,
"nome": "Gustavo Henrique",
"status": "Ativo"
},
"mensalidade": {
"status": "Pago"
}
},
{
"aluno": {
"id": 656,
"nome": "Vivien Jacobs",
"status": "Ativo"
},
"mensalidade": {
"status": "Débito"
}
}
]
}
My service:
import { IStudent } from './../students';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { HttpErrorResponse } from '@angular/common/http/src/response';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class StudentsService {
public alunos = [];
// LIST STUDENTS URL
public list_students_url = 'http://localhost:8000/api/aluno/list';
constructor(private http: HttpClient) { }
// Pega todos os alunos.
getAlunos(): Observable<IStudent[]>
{
return this.http.get<IStudent[]>(this.list_students_url)
.catch(this.errorHandler);
}
errorHandler(error: HttpErrorResponse)
{
return Observable.throw(error.message || "Server error");
}
}
My interface:
export interface IStudent {
alunos: {
aluno: {
id: number,
nome: string,
status: string,
},
mensalidade: {
status: string
}
}
}
My component:
import { StudentsService } from './services/students.service';
import { Component, OnInit, Input } from '@angular/core';
import { IStudent } from './students';
@Component({
selector: 'app-students',
templateUrl: './students.component.html',
styleUrls: ['./students.component.css']
})
export class StudentsComponent implements OnInit {
public students = [];
public errorMsg;
constructor(private service: StudentsService) { }
ngOnInit() {
this.service.getAlunos()
.subscribe( data => this.students = data,
error => this.errorMsg = error);
//console.log(this.students);
}
}