Issue with rendering images retrieved from JSON data

Struggling with displaying images in my Ionic and Angular pokedex app. The JSON file data service pulls the image paths, but only displays the file path instead of the actual image. Any ideas on what might be causing this issue?

Sample snippet from the JSON file:

{
    "pocketMonsters": [

        {
            "pokemonName": "Bulbasaur",
            "pokedexNumber": "001",
            "description": "Bulbasaur can be seen napping in bright sunlight...",
            "pokemonImage": "<img src='assets/imgs/bulbasaur.png' />"
        },

        {
            "pokemonName" : "Ivysaur",
            "pokedexNumber" : "002",
            "description" : "",
            "pokemonImage" : "<img src='assets/imgs/ivysaur.png' />"
        },

Template code that I've tried:

<ion-header>
  <ion-navbar>
    <ion-title>
      Pokedex
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      {{pocketMonster.pokemonImage}}
    </ion-item>
   </ion-list>
  

  <!--<div *ngIf="pocketMonsters.length"></div> -->

</ion-content>

Includes the home component and data service:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { pokemonDataService } from '../../providers/data/data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  pocketMonsters = [];
  searchQuery: string = '';
  
  // Constructor and ionViewDidLoad methods...

}

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
 
@Injectable()
export class pokemonDataService {
 
    data: any;
 
    constructor(public http: Http) {
 
    }

    getAllPokemon() {
        if (this.data) {
            return Promise.resolve(this.data);
        }

        return new Promise(resolve => {

            this.http.get('assets/data/pokemon.json').map(res => res.json()).subscribe(data => {
                this.data = data.pocketMonsters;
                resolve(this.data);
            });

        });
    }
 }

Answer №1

Here is an example to try:

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      <img src="{{pocketMonster.pokemonImage}}">
    </ion-item>
   </ion-list>

or you can check out the alternative approach here

  <ion-list>
    <ion-item *ngFor="let pocketMonster of pocketMonsters;">
      {{pocketMonster.pokemonName}}
      <img [src]="pocketMonster.pokemonImage">
    </ion-item>
   </ion-list>

Make sure in your data, only include the asset location without any pre-made tags:

    {
        "pokemonName" : "Ivysaur",
        "pokedexNumber" : "002",
        "description" : "",
        "pokemonImage" : "assets/imgs/ivysaur.png"
    },

This assumes that your image is located at that specified path.

You can also refer to this resource here, but usually there is no need to include HTML snippets in this scenario.

In my opinion, it's generally not a good practice to do so in most cases™.

Answer №2

If your data is structured like this:

    {
        "name": "Charmander",
        "id": "004",
        "description": "Charmander prefers hot places. When it rains, steam is said to spout from the tip of its tail.",
        "image": "<img src=’assets/imgs/charmander.png’ />"
    },

To display the image using the data provided, you can use innerHTML:

<span innerHTML="{{pokemon.image}}"></span>

This should help you in displaying the image correctly, but make sure to also consider @bgse’s advice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Angular 2 Fallback Route Failure

My current project is using Angular 2 Webpack Starter but I am having trouble with the fallback route. In my app.routes.ts file, I have defined the routes as follows: import { Routes } from '@angular/router'; import { HomeComponent } from &apos ...

Encountering a CORS error while utilizing a Node.js Express API with an Angular frontend

While developing an API using Node.js, Express, and MongoDB, I encountered a CORS error when trying to call the API from an Angular application. Strangely enough, the API works fine when deployed on Render, but throws an error locally. Error: Access to XM ...

Exploring type definition for function arguments in TypeScript and React

There is a high-order component (HOC) designed to store the value of one state for all input and select elements. The output function accepts arguments ({text: Component, select: Component}). An error is displayed while typing an argument: TS2322: Type &ap ...

Developing a Typescript "Map" type using numerical enumerations

In my Typescript project, I came across the need to create record types with numeric enums: enum AxisLabel { X = 0, Y = 1 } export const labelLookup: Record<AxisLabel, string> = { [AxisLabel.X]: "X axis", [AxisLabel.Y]: "Y Axis" }; However, I w ...

The observable HTTP map appears to be more of a representation rather than a concrete entity

I seem to be struggling with understanding Typescript I expected the returned observable to have a method getTitle(), but it seems to be missing. Instead, I am getting an object that resembles AttachableContentModel without that particular method. What is ...

Issue detected in Angular 2 Heroes Tutorial: The element with the selector "my-app" was not found in the document

Currently, I am in the process of following along with the Heroes tutorial on the official angular website. The project was created using CLI and everything seemed to be working smoothly up until Part 6 on Routing: https://angular.io/tutorial/toh-pt5 In ...

Is it possible to loop through a subset of a collection using *ngFor?

Is it possible to iterate through a specific range of elements in a collection using *ngFor? For instance, I have a group of checkboxes with their form control name and label specified as follows: [{id: 'c1', label: 'C1'}, ...] Assum ...

Error: The observable pipe method is not defined in Angular testing suite

I am struggling with writing a unit test for a photo upload method due to the following error: Failed: this.task.snapshotChanges(...).pipe is not a function TypeError: this.task.snapshotChanges(...).pipe is not a function. To simplify, I have included al ...

Angular array of considerable size

Dealing with a massive array of 30,000 items can be quite daunting, especially when it comes in as a stream using grpc-web. Currently, I'm fetching the data from grpc.client() and populating an array before displaying it using *ngFor. However, I' ...

Maintain the nullability of object fields when casting

I have been working on a type called DateToNumber that converts all the Date properties of an object to number. Here is what I have come up with so far: type LiteralDateToNumber<T> = T extends Date ? number : T extends Date | null ? number | nu ...

How can I dynamically change the prefix in an angular router?

In my Angular app, I have two main routes: dashboard and login: www.example.com/dashboard www.example.com/auth/login These routes are defined as follows: const routes = [ { path: 'dashboard', component: DashboardComponent }, { path: 'auth ...

The table is appearing incorrectly on the screen

I am working on displaying a list of elements in a table. To achieve this, I have created two components - the tableComponent and the tableitemComponet. In the tableComonent, I have implemented the following: <table class="table"> <thead> ...

Having trouble retrieving a value from the img.onload event handler. A 'boolean' type error is being thrown, indicating it cannot be assigned to type '(this: GlobalEventHandlers, ev: Event) => any'

In my Angular application, I have implemented a method that verifies the size and dimensions of an image file and returns either false or true based on the validation result. Below is the code snippet for this function: checkFileValidity(file: any, multipl ...

Best practices for maintaining editable ag-grid cells

Using ag-grd-ng2 (ag-grid for Angular2), I have implemented editable cells and successfully propagated updates to the server. This was achieved by utilizing the gridOptions.onCellValueChanged event. Within my column definition, the properties are set as ...

Running Angular 2 build files with express.js: A step-by-step guide

Currently, I am trying to run index.html which is generated from an Angular2 app after using ng build. I attempted to use the following two lines of code individually, but unfortunately, neither of them worked for me: 1. app.use(express.static(path.resolv ...

The confirm alert from Material UI is being obscured by the dialog

How can I ensure that a material ui dialog does not hide the alert behind it when confirming an action? Is there a way to adjust the z index of the alert so that it appears in front of the dialog? import Dialog from "@material-ui/core/Dialog"; i ...

Creating Dynamic Ionic Slides with Additional Slides Inserted Before and After

Hello, I am currently using ngFor to generate a set of 3 slides with the intention of starting in the middle so that I can smoothly slide left or right from the beginning. When I slide to the right, I can easily detect when the end is reached and add anot ...

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

Tips for setting up a responsive dropdown field in an Angular 6 reactive form for an Edit page

When creating a drop down field with API values, I encountered an issue where all data was displayed on the edit page instead of just the previously stored value. The drop down field showed all options instead of the selected one. Below is the code for the ...

Customizing number input types in Angular 2 - the perfect solution

Attempting to incorporate a time picker using HTML5 input type number in Angular2. The code snippet below illustrates the setup: <input type="number" [(ngModel)]="hour" (change)="checkHours();" name="one" min="1" max="12"> <input type="number" ...