es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Los datos JSON locales no se muestran en la página HTML en Ionic 5.

Solo quería imprimir los datos JSON de mi archivo local .json, estoy obteniendo los valores del JSON en la consola, pero no se están imprimiendo en la página HTML.

home.page.ts

import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  cats:any;
  constructor(public http:HttpClient) {
    this.loadData();
  }

  ngOnInit() {

  }

  loadData(){
    let data:Observable<any>
    data = this.http.get('assets/backend/db.json');
    data.subscribe(result => {
      this.cats = result;
      console.log(this.cats);
    },
    (err) => {
      alert('failed loading json data');
   });
  }
}

home.page.html

<ion-item *ngFor="let cat of cats">
   <ion-card>
      <ion-card-header>
         <ion-card-title>Name: {{cat.AltName}}</ion-card-title>
         <ion-card-subtitle>Origin: {{cat.Origin}}</ion-card-subtitle>
         <ion-card-subtitle>Average LifeSpan: {{cat.Averagelife}}</ion-card-subtitle>
      </ion-card-header>
      <ion-card-content>
         <img src={{cat.url}} alt="">
         Breed Description: {{cat.BreedDesc}}
      </ion-card-content>
   </ion-card>
</ion-item>

Estoy obteniendo esto en la consola:


animals: Array(9)
0: {AltName: 'Longhair or Persian Longhair', Origin: 'Iran', Averagelife: '12-17 years', BreedDesc: 'Long haired breed of cat that has a short round fa…a thick coat , large eyes and a shortened muzzle.', url: 'https://troubleandtrix.com/media/3kzp0xhw/persian-…crop&width=1238&height=640&rnd=132521132574070000'}
1: {AltName: 'American Burmese, British Burmese', Origin: 'Thailand', Averagelife: '10-17 years', BreedDesc: 'Appears in 2 forms – American and British. The Bri… ones are broader and shorter with a flat muzzle.', url: 'https://www.purina.co.uk/sites/default/files/2021-02/CAT%20HERO_0005_Burmese.jpg'}
2: {AltName: 'Scot Fold, Lops, Folds', Origin: 'Scotland', Averagelife: '11- 15 years', BreedDesc: 'It is a medium sized cat weighing 4-6 kg. The coat…or short-haired and ears can be normal or folded.', url: 'https://d17fnq9dkz9hgj.cloudfront.net/breed-upload…cottish-fold-detail.jpg?bust=1535567146&width=355'}
3: {AltName: 'Bobbed tail cat', Origin: 'United States', Averagelife: '11- 15 Years', BreedDesc: 'These have a short to medium built body with short…Ears are medium sized and eyes are almond shaped.', url: 'https://d17fnq9dkz9hgj.cloudfront.net/breed-upload…American-Bobtail-01.jpg?bust=1539031086&width=355'}
4: {AltName: 'Bengoli Cat', Origin: 'United States', Averagelife: '14-16 Years', BreedDesc: 'Bengal cats are a hybrid of the Asian Leopard Cat …tern and swirly marbled. They have a white belly.', url: ''}
5: {AltName: 'Ankara', Origin: 'Turkey', Averagelife: '12- 18 years', BreedDesc: 'These have long silky coats with round bodies. They are intelligent, playful and loyal with humans.', url: 'https://media.istockphoto.com/photos/bengal-cat-pi…=0&h=fSyuzbgVaj1-ndIhUJq1R2WqE2UveUUeA4iFADdt1CE='}
6: {AltName: 'Spangle', Origin: 'California', Averagelife: '9-16 years', BreedDesc: 'This breed looks similar to a leopard in appearanc…a spotted muscular body with large whisker pads.', url: 'https://allaboutcats.com/wp-content/uploads/2020/10/The-California-Spangled-Cats.jpg'}
7: {AltName: 'Mau', Origin: 'Egypt', Averagelife: '13-16 Years', BreedDesc: 'They are slender and muscular cat that are loyal t…egs are comparatively shorter than the hind legs.', url: 'https://vetstreet.brightspotcdn.com/dims4/default/…0568d634f%2Ffile%2FEgyptian-Mau-2-645mk062211.jpg'}
8: {AltName: 'Sacred Birman, Sacred Cat of Burma', Origin: 'France', Averagelife: '12-16 Years', BreedDesc: ' It is a domestic cat breed having medium sized an…that are sapphire blue in color and a roman nose.', url: 'https://st4.depositphotos.com/1004592/24111/i/600/…ck-photo-birman-kitten-front-white-background.jpg'}
length: 9

Este es el error que estoy obteniendo en la consola:

ERROR Error: No se puede encontrar una diferencia admitiendo el objeto ‘[object Object]’
de tipo ‘objeto’. NgFor solo admite la vinculación a Iterables como
matrices.

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    El problema aquí es que la variable cats no está definida correctamente como un array en el componente. Para solucionarlo, agregue un tipo a la variable cats en el componente de la siguiente manera:

    cats: Array<any>;
    

    O alternativamente, utilice la sintaxis abreviada:

    cats: any[];
    

    Luego, en el método loadData(), inicialice cats como un array vacío antes de asignarle el valor del archivo JSON:

    loadData(){
      let data:Observable<any>
      data = this.http.get('assets/backend/db.json');
      data.subscribe(result => {
        this.cats = [];
        this.cats = result.animals;
        console.log(this.cats);
      },
      (err) => {
        alert('error al cargar datos json');
     });
    }
    

    Al inicializar la variable cats como un array vacío y luego asignarle el valor obtenido del archivo JSON, la directiva *ngFor en la plantilla HTML podrá iterar correctamente sobre el array y mostrar los valores.

Comments are closed.