The console is displaying an undefined error for _co.photo, but the code is functioning properly without any issues

I am facing an issue with an Angular component.

When I create my component with a selector, it functions as expected: it executes the httpget and renders a photo with a title. However, I am receiving two errors in the console:

ERROR TypeError: "_co.photo is undefined"
    View_PhotoHolderComponent_0 PhotoHolderComponent.html:2

and

ERROR CONTEXT 
...
PhotoHolderComponent.html:2:8
    View_PhotoHolderComponent_0 PhotoHolderComponent.html:2

In my HTML, I have:

    <div class="photo-holder">
    <h2>{{photo.title}}</h2>
    <img src="{{photo.url}}">
    </div>

and in my TypeScript file:

import { Component, OnInit } from '@angular/core';
import { Photo } from './photo'
import { PhotoDeliveryService } from '../photo-delivery-service.service'

@Component({
  selector: 'app-photo-holder',
  templateUrl: './photo-holder.component.html',
  styleUrls: ['./photo-holder.component.css']
})
export class PhotoHolderComponent implements OnInit {

  photo:Photo
  constructor( private photoService : PhotoDeliveryService) {
  }

  ngOnInit() {
    this.photoService.getRandomPhoto().subscribe((data: Photo) => this.photo = {...data})
  }

}

and in the service file :

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Photo } from './photo-holder/photo'

@Injectable({
  providedIn: 'root'
})
export class PhotoDeliveryService {
  value : Number
  url : string

  constructor(private http: HttpClient) { 
    this.url = "https://jsonplaceholder.typicode.com/photos/";
    this.value = Math.floor(Math.random() * 10) + 1; 
  }

  getRandomPhoto()  {
     return this.http.get<Photo>(this.getUrl())
  }

  getUrl(){
    return this.url + this.value;
  }

}

I suspect that this issue may be due to binding properties before the query results are returned. How can I resolve this problem? Is there a way to wait for the query to finish, or is there another type of issue at play here?

Answer №1

The reason for the error you are experiencing is due to the fact that the template bindings are resolved before your service can resolve, resulting in the photo object being undefined at that time.

To address this issue, one approach is to initialize the photo object and then use ChangeDetectorRef to detect changes and reflect the value returned by the service.

photo:Photo = {
    title:'',
    url:''
};
constructor( private photoService : PhotoserviceService, private cdr:ChangeDetectorRef) {
}

ngOnInit() {
    this.photoService.getRandomPhoto().subscribe((data: Photo) => {
        this.photo =  data;
        this.cdr.detectChanges();
    });
}

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

CircularProgress Error: Unable to access 'main' property as it is undefined

As I delve into the realm of React and Next.js, I am faced with the task of upgrading from Node V16 to Node V18. One significant change in this upgrade is migrating from MUI v4 to v5. Currently, my project utilizes the following packages: "@emotion/ba ...

What could explain why the event listener functions properly on the initial call but fails on subsequent calls?

Currently, I am working on a bootstrap carousel where the "Previous" button is hidden on the first slide and the "Next" button is hidden on the last slide. Now, I want to disable the next button on the second slide (and eventually all slides with iframe vi ...

Tips for resolving the error "Cannot access the title property of undefined" when utilizing NextJS prerendering

I am preparing this page in advance for a specific post within my Next.js application: import Head from 'next/head'; import Link from 'next/link'; import client from '../../lib/apollo/client' import POSTS_WITH_SLUGS from &apos ...

Console Error: Attempting to set the 'className' property of null object results in an

I'm experiencing difficulties setting up the code. The function should display all songs by a specific artist when their name is entered and the button is pressed. JavaScript file: /** * Utilizes AJAX to request data about artists from an online sou ...

Issue encountered while authenticating client secret from backend for newly created Stripe subscription

There seems to be an issue with confirming the client secret sent from the express backend to the frontend, specifically in a React Native-based mobile application. The clientSecret is being sent in the same manner as described above. On the frontend Rea ...

External function does not support jQuery types

In my theme.js file, I currently have the following code: jQuery(function ($) { accordion($) }) const accordion = ($) => ... By placing the accordion function directly into the jQuery function, Typescript is able to assist with the installed jquery ...

quickest method for attaching a click listener to dynamically added elements in the document object model

When adding multiple elements to the DOM, how can we ensure that these elements also have a click handler attached to them? For instance, if there is a click handler on all elements with the "canvas-section" class, and new "canvas-section" elements are con ...

I am encountering difficulty in printing multiple documents from FireStore

I am facing an issue where I can successfully retrieve and print all documents from a Firestore collection one by one using console.log(). However, when attempting to display these documents on the screen, only the most recent document is showing up. Here ...

How to retrieve the value of a selected item in primeng using p-dropdown and angular

Encountering an issue when trying to send the selected item value while iterating over an array of strings like: "BMW", "FERRARI", "AUDI", "BENTLY" Here is the structure of my HTML: <p-dropdown optionLabel="type" [options]="cars" formControlName="name" ...

Issue: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables like Arrays. Solution needed to resolve this

Code snippet for a service that returns JSON data export class EmployeeServiceService { constructor(private _http:Http) { } GetEmployees(): Observable<IEmployee[]>{ debugger; return this._http.get("http://localhost:2724/a ...

Tips for incorporating the .click function with an overlay

Having some trouble using the .click function in conjunction with jQuery Tools overlay. HTML: <p id="click">Click here:</p> <div class="pop"> <div> <p>Insert text here</p> </div> </div> jQuery func ...

Guide to accessing object items in v-for in VueJs

Upon inspection, the following results are being displayed: In the Vue template code provided: <select class="form-select" v-model="post_format.wpml_language"> <option v-for="(lang, index) in wpml_languages" :value="lang">{{lang}} {{index}} ...

The width of the table remains consistent

I have created a division that includes two tables stacked on top of each other. However, I am facing an issue where the width of the second table remains fixed and does not change even when I try to increase it. Here is the code snippet below: functio ...

Transform a delimited string and an array of objects into a new format

Is there a way to easily convert a delimited string into an array of objects with data binding functionality? ng-list is suitable for arrays of strings. However, I have an array of objects where I want to delimit the text property for easy editing. Works ...

The playwright brings the curtain down on a blank page without a single word

I am working with code snippets const {chromium} = require('playwright'); (async () => { const userDataDir = '\NewData'; const browser = await chromium.launchPersistentContext(userDataDir,{headless:false}); const pag ...

Error: Angular7 Unable to locate namespace 'google'

I am currently utilizing the import { MapsAPILoader } from '@agm/core'; package to enable auto-complete address search functionality. However, I have encountered an error message stating cannot find namespace 'google'. The error occu ...

Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality? Here's the code snippet: <md-s ...

Create an input element using JavaScript/jQuery

Looking for some help with Javascript on a simple task. When a specific option is chosen, I want to add an input field to a div element. <select name="amount" > <option value="50">50$</option> <option value="100">100$</o ...

One class seems to be causing issues with hover functionality while the other works perfectly fine

HTML: <div class="channellist"></div> Through the use of Ajax, I am able to dynamically retrieve channels when the page loads and then append them within the channellist container. Once appended, my HTML structure appears as follows: <div ...

"Submit form data without reloading the page using the $_

I have an associative array that I am using to display images. I want to randomly select two or more pictures from these images with my code, but I have a couple of questions: How can I enhance the efficiency of my code? And is there a way to use JSON or ...