Ahmed Shaarawy
Ahmed Shaarawy

Reputation: 59

Cannot read property 'image' of undefined angular 6

When trying to get the details it renders to the dom but it gives an undefined error. here is an image to show

enter image description here

This is 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();
        }
      }
    );
  }

}

And this is the getBook function from service

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

Upvotes: 1

Views: 6458

Answers (2)

RamAnji
RamAnji

Reputation: 470

When u refresh the page it initially calls the ngOninit method.

here initially if the condition becomes false and it chooses else...

here it calls getAsyncData()...

this.book = this.books.filter(book => book.id === this.id)[0];

in this filter book.id is empty so it throws an undefined error.

Upvotes: 0

fjc
fjc

Reputation: 5815

The issue with this is normally that you use a line such as

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

in your code. When the component is first rendered, your book object is still undefined (see book: Book;: no value definition here).

One solution is to wrap references to book in an *ngIfed block:

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

Or, alternatively, if it's just this single image, do

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

Or alternatively, if you don't mind the img being in your DOM with an empty src:

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

Upvotes: 11

Related Questions