Angular 6 - Ngfor only Supports Binding to Iterables such as Arrays

Asked

Viewed 7,675 times

0

Error: Cannot find a differ supporting Object '[Object Object]' of type 'Object'. Ngfor only Supports Binding to Iterables such as Arrays.

I have model:

import { Classroom } from "./classroom.model";

export class Student {
    public id : string;
    public name: string;
    public classroom: Classroom[];
    public mother: string;  
    public phone_mother: string; 
    public father: string;    
    public phone_father: string;
    public address: string;

    constructor(id : string, name: string, classroom: Classroom[], mother: string, phone_mother: string, father: string,  phone_father: string, address: string, ){
        this.id = id,
        this.name = name;
        this.mother = mother;
        this.father = father;
        this.phone_mother = phone_mother;
        this.phone_father = phone_father;
        this.address = address;
        this.classroom = classroom;
    }
}

My Service:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';

import { Student } from "../models/student.model";
import { Classroom } from "../models/classroom.model";

@Injectable()
export class StudentsServices
 {   
    private _url = 'https://localhost:3000/api/aluno'
       
    constructor(private http: Http){}

getStudents(){
    return this.http
                .get(this._url)
                .pipe(map((response : Response) => {
                    return <Student[]>response.json();
                }));                         
}


    getEstudantes(): Observable<Student[]> {
        return this.http.get(this._url)
                        .pipe(map(res=>res.json()));                        
     } 

}

My Component:

import { Component, OnInit } from '@angular/core';

import { StudentsServices } from '../services/students.services';
import { Student } from '../models/student.model';

@Component({
  selector: 'app-students',
  templateUrl: './students.component.html',
  styleUrls: ['./students.component.css'],
  providers: [StudentsServices]
})
export class StudentsComponent implements OnInit {  
  _students: Student[] = [];  

  constructor(private services: StudentsServices) { }

  getStudents(): void {
        this.services.getStudents()
                     .subscribe(
                        data => this._students = data,
                        error => console.log("Student Service Error: " + error)
                     )
  }  

  getEstudantes() {
    this.services.getUsers()
                    .subscribe(
                      data => this._students = data,
                      error =>  console.log("Student Service Error: " + error));
  }

  ngOnInit() {    
        this.getStudents();

        //this.getEstudantes();

        console.log(this._students);
  }
}

and this is my HTML

<div class="row">
    <table class="table">
        <thead class="thead-inverse">
            <tr>
                <th class="text-center">ID</th>
                <th class="text-center">Nome</th>
                <th class="text-center">Mãe</th>
                <th class="text-center">Pai</th>
                <th class="text-center">Telefone da mãe</th>
                <th class="text-center">Telefone do Pai</th>
                <th class="text-center">Endereço</th>
                <th class="text-center">Turma</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let student of _students">
                <td class="text-center">{{student.id}}</td>
                <td class="text-center">{{student.name}}</td>
                <td class="text-center">{{student.mother}}</td>
                <td class="text-center">{{student.father}}</td>
                <td class="text-center">{{student.phone_father}}</td>
                <td class="text-center">{{student.phone_mother}}</td>
                <td class="text-center">{{student.address}}</td>
                
            </tr>
        </tbody>
    </table>
</div>

These are the date inserir a descrição da imagem aqui

  • tries Let student of _student.students

  • I’ve tried, it says students don’t exist ):

  • 1

    Make a Demon in stackblitz

  • Please do not post image as code. It is possible to edit your question with the code itself?

  • https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas/5485#5485

  • If you post your code as text I do a stackblitz and see what’s wrong.

  • I’ve changed it to code, if you can help me.

  • What comes out when you play the url in your browser? You can add a print?

  • {"students":[{"_id":"5b0af0b35af000143a39af","name":"Adriano","class":{"_id":"5b0aee26539af000143a39ab","Description":"CLASS 304"}},{"_id":"5b0af0b7539af000143a39b0","name":"Such","class":{"_id":"5b0aee26539af000143a39ab","Description":"CLASS 304"}},{"_id":"5b0af539af000143a39b1","name"":"Gustavo","class":{"_id":"5b0aee26539af000143a39ab","Description":"TURMA 304"}},{"_id":"5b0af0be539af000143a39b2","name":"Vinicius","class":{"_id":"5b0aee26539af000143a39ab","Description":"TURMA 304"}}],"total":4}

Show 4 more comments

3 answers

0


My problem was mapping the data that came from the api to the variables that were in my model. In the api the data was coming in Portuguese and in my model was in English.

So I was able to specify which data I wanted in my service call "date.":

getStudents(): void {
        this.services.getStudents()
                     .subscribe(
                        data => this._students = data.alunos,
                        error => console.log("Student Service Error: " + error),
                        () => console.log('Done.')
                     )
  }  

I had to adjust the service too:

  getStudents(){
        return this.http
                    .get(this._url)
                    .pipe(map((response => response.json())));                         
    }

0

Try to initialize the Students variable when you declare it:

_students:Student[]= []

this.services.getStudents()
.pipe(map(student=>student.alunos))
.subscribe(alunos=>this._students=alunos)

0

Your problem lies in the asynchronousness of the processes, your code in the . html is running before you can even feed the variable into your .ts. For this problem you need to work with promises or Promise. an example

Method within the service:

public getProjetos(): Promise<Projeto[]>{
return this.http.get(`${this.url_api}projetos/`)
.toPromise()
.then((resposta: any) => {
    console.log("Teste: " + resposta)
    return resposta.json()
})

service call:

this.projetoService.getProjetos().then((projetos: Projeto[]) => {
  this.projetos = projetos

})
  • Opa is Angular 6, not Angularjs

  • Yes, this practice also works for Angular 6, I solved the problem with Promise, but you can solve it with observable, but I still don’t understand this practice

Browser other questions tagged

You are not signed in. Login or sign up in order to post.