1
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".
Response from the API :
{
"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);
}
}
To community gives the option to put codes in the body of the question, if you can do the favour of edit and put, just paste the code, select and hit the shortcut CTRL+K that will format the same..
– NoobSaibot
Got it, corrected =)
– Mateus Henrique
Your interface is incorrect, you are not declaring the array that is in the JSON body
– André Roggeri Campos