1

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];
  }
3
  • can you also share the html code Commented Oct 10, 2018 at 9:34
  • You have no reference to an image property in your code. Commented Oct 10, 2018 at 9:34
  • You know it was working fine but when refresh the data is gone, Do you know how to solve this?? From your comments. Solution you have to once you get value then you have to set some common service or some other way like local storage and you can get. Because you are capture the data via routerparams. Commented Oct 10, 2018 at 10:31

2 Answers 2

11

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 }}" />
Sign up to request clarification or add additional context in comments.

3 Comments

it just not the image it gives to the whole book details like it is not there.
You know it was working fine but when refresh the data is gone, Do you know how to solve this??
why are u using [0]?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.