Home > Software engineering >  ngfor does not work when displaying multiple cards in ionic angular
ngfor does not work when displaying multiple cards in ionic angular

Time:07-15

Good morning, I am consuming an api that I made in laravel and so far if I am bringing the data well, since I tested them by the console. Now the problem is that when I generate some cards in ionic to show the data that I am consuming does not show me anything, all this I do with a ngfor, when I remove it shows the example card.

code and sample

post-list component

<ion-list>
    <ion-list-header> Usuarios </ion-list-header>
    <app-post-item *ngFor=" let item of usaurios" [usuario]="item">
    </app-post-item>
</ion-list>

post-item component

<ion-item>
    <ion-avatar slot="start">
        <img src="https://i.pravatar.cc/150?img=2" />
    </ion-avatar>
    <ion-label>
        <h2>Finn</h2>
        <h3>I'm a big deal</h3>
        <p>Listen, I've had a pretty messed up day...</p>
    </ion-label>
</ion-item>

Sample enter image description here

The moment I remove the *ngFor=" let item of usaurios" [user]="item" in the post-list component now I get this enter image description here

I really don't know what I'm doing wrong or if I have a mistake....

logic

user.service

export class UserService {
    public url: String = environment.url;
    public usuarios$ = new Subject<Usuario[]>(); 
    public usuario$ = new Subject<Usuario>();

    public usuarios: Usuario[] = [];
    public usuario: Usuario;
    constructor(public http: HttpClient) {}
    all$(): Observable<Usuario[]> {
        return this.usuarios$.asObservable();
    }
    all(): Observable<any> {
        this.usuarios = [];
        return this.http.get<Usuario[]>(this.url   'usuario').pipe(
            map ((res: any[]) => {
                Array.from(res).forEach((item: any) => {
                    this.usuario = new Usuario();
                    this.usuario.set(item);
                    this.usuarios.push(this.usuario);
                });
                this.usuarios$.next(this.usuarios);
                console.log(res);
            })
        );
    }
}

post-list.component

export class PostListComponent implements OnInit {
    public usaurios: Usuario[] = [];
    public usuario: Usuario;
    public usuarioSubscription = new Subscription();

    constructor(
        public userservice: UserService
    ) {}

    ngOnInit() {
        this.usuarioSubscription = this.userservice.all$().subscribe((res: Usuario[])=>{
            this.usaurios = res;
        });
        this.userservice.all().subscribe(res => {
            console.log('Listo...');
        });
    }
}

console: mi consola

post-list-component.ts

import { Component, Input, OnInit } from '@angular/core';
import { Usuario } from 'src/app/models/usuario';

@Component({
    selector: 'app-post-item',
    templateUrl: './post-item.component.html',
    styleUrls: ['./post-item.component.scss'],
})
export class PostItemComponent implements OnInit {
    @Input() usuario: Usuario;
    constructor() {}

    ngOnInit() {}
}

CodePudding user response:

From what I see in your code, you are doing a console.log(res), which shows the data coming from API as { data: [...] } format. But you are running your loop on res, meaning the loop doesn't actually insert any value in this.usuario. That's why when you are running *ngFor=" let item of usaurios", you don't see anything, because your array is blank (usaurios is []).

Try Array.from(res.data).forEach((item: any) => { ... } and see if that solves your problem. You can also add console.log(this.usuario) to verify if your array is correctly populated.

CodePudding user response:

I think the error was in the forEach when adding them. I applied another logic using only the map

code

all(): Observable<any> {
        return this.http.get(`${this.url}usuario`).pipe( // <-- URL and pipe is for 404 error
            map((res: any) => {
                this.usuarios = res.data; // receives the data and stores it in the users variable
                this.usuarios$.next(this.usuarios); // sends the data to the usuarios$ variable so that it can be subscribed in the component
                return this.usuarios; // returns the data that is in the users variable
            }),
            catchError(err => {
                console.log(err);
                return err;
            }),
        );
    }

and it did work for me

  • Related