Angular 6 is throwing an error message stating that it cannot access the 'image' property of an undefined object

Having trouble retrieving the details, as it is rendering to the dom with an undefined error. Check out this image for reference:

https://i.sstatic.net/YB2Lf.jpg

Welcome to the Book Details Component

export class BookDetailsComponent implements OnInit {
  book: Book;
  books: Book[];
  id: string;

  constructor(private route: ActivatedRoute, private booksService: BooksService, private http: Http) { }

  async getAsyncData() {
    this.books = await this.http.get('/assets/books.json').toPromise().then(
      data => this.books = data.json().books
    );
    this.book = this.books.filter(book => book.id === this.id)[0];
  }

  ngOnInit() {
    this.route.params.subscribe(
      (params: Params) => {
        this.id = params['id'];
        
        if (this.book) {
          this.book = this.booksService.getBook(this.id);
        } else {
          this.getAsyncData();
        }
      }
    );
  }

}

Additionally, here's the getBook function from service:

getBook(id: string) {
    return this.books.filter(book => book.id === id)[0];
  }

Answer №1

The issue arises when you include a line like this

<img src="{{ book.image }}" />

in your code. At the initial rendering of the component, the book object is still undefined (as seen in book: Book; without a defined value).

To address this, one option is to enclose references to the book in an *ngIf statement:

<ng-container *ngIf="book">
    <img src="{{ book.image }}" />
</ng-container>

Alternatively, if it pertains only to this particular image, you can do this:

<img src="{{ book.image }}" *ngIf="book" />

Or if having the img tag in the DOM with an empty src doesn't bother you:

<img src="{{ book?.image }}" />

Answer №2

Upon refreshing the page, the ngOninit method is triggered.

If the initial condition evaluates to false, it will proceed to the else block...

Subsequently, the getAsyncData() function is invoked...

The value of this.book is assigned based on a filter operation that matches book id with the provided id.

An error occurs in this filter operation because book.id is empty, resulting in an undefined error.

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

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Jhipster entity authentication

For my latest project with JHipster, I decided to incorporate Angular 2 and MongoDB. One of the entities I created is a 'doctor' with attributes such as name (string), login (string), password (string), and specialty (string). Now I want to enabl ...

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

Angular Universal involves making two HTTP calls

When using Angular Universal, I noticed that Http calls are being made twice on the initial load. I attempted to use transferState and implemented a caching mechanism in my project, but unfortunately, it did not resolve the issue. if (isPlatf ...

Storing dates using Angular 2 and JSON for efficient data management

I've encountered a challenging issue with my Angular 2 application. I'm attempting to organize my API (MongoDB) in such a way that each new "post" added by the admin can be retrieved by date (not time) on the front end. Here's an example of ...

Trouble with Angular toggle switch in replicated form groups

Currently, I have a form group that contains multiple form controls, including a toggle switch. This switch is responsible for toggling a boolean value in the model between true and false. Depending on this value, an *ngIf statement determines whether cert ...

Using Meteor methods in a Meteor and Ionic application: A guide

After building the web app with Meteor, I am now looking to develop a new app utilizing both Meteor and Ionic technologies. My goal is to leverage the existing Meteor methods in my Ionic app without duplicating efforts for mobile development. Any suggestio ...

Angular - What causes variables to lose data after component changes?

Having an issue with two components - one creating and changing an array, and the other getting the array. The problem is that when retrieving the array in the second component, it only shows the default empty data. Code for array creation: export cla ...

Angular 4: Is there a correlation between the level of complexity in componentizing HTML and the difficulty of passing variables to sibling components?

Do you ever wonder if the way you're approaching something is correct? I tend to believe that breaking down an HTML page into as many sub-components as possible is a good practice. For example, let's look at this situation: An existing compone ...

How can variables within nested ngFor loops be referenced in Angular 1.5 compared to Angular 10?

This particular piece of code was functional in Angular 1.5. It featured a condition where the <tr> element would only be displayed if the 'showFields' flag for that specific row key was set to true. <table> <ng-container *ngIf=& ...

Is it possible for a typed function to access object properties recursively?

Is there an efficient method in TypeScript to type a function that can recursively access object properties? The provided example delves two levels deep: function fetchNestedProperty<T, K extends keyof T>(obj: T, prop1: K, prop2: keyof T[K]) { r ...

The process of switching from timestamp to date varies depending on whether you are working locally or on a server

Currently, I am in the process of developing an app using Firebase as the server and Flutter for the frontend. The situation I am facing is that when I upload a new document with a timestamp containing the current time in this format: "timestamp": DateTim ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...

Is it possible to import a class from a different project or module in TypeScript?

I am attempting to modify the build task in Typescript within this specific project: https://github.com/Microsoft/app-store-vsts-extension/blob/master/Tasks/app-store-promote/app-store-promote.ts I am looking to incorporate an import similar to the one be ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

Using Angular CLI with ES6 instead of TypeScript for your development needs can offer a

Is there a way to utilize an ES6 transpiler such as Babel instead of TypeScript in an Angular CLI project? Are there any specific flags for specifying the script language, similar to using --style? Thank you. ...

"Utilize the handle property of a component when interacting with the window.onclick

In my component, I have a property called enableButtons which is set to true when I click on an ion-menu label. However, I want this property to revert to false if I click anywhere else. Here's the code I tried: export class ProfilePage implements OnI ...

The negation operator in Typescript is failing to negate as expected

When a user changes a multiselect element, there is a function that runs to control the visibility of an error message: getVisibility(multiselect) { if ((multiselect.selectedCategories.length < 1 && !multiselect.allSelected) && th ...

Guide to Setting Up Infinite Scroll with Next JS SSG

I recently built a markdown blog using the Next Js documentation and incorporated Typescript. When trying to retrieve a list of blog posts, I utilized getStaticProps as recommended in the documentation. However, my attempts with certain npm packages were u ...