Search code examples
angulargoogle-books

How to transfer data json (Google books API) with dialog


I have transmitted data from Google books API in a dialog and it seems to work, but when I try to display the data, it gets complicated. If I try to display the element "kind" or "totalItems" it is displayed correctly, but if I try to display "items.something" it doesn't work.

ERROR TypeError: Cannot read property 'title' of undefined

How can I display the content of "items"?

API: https://www.googleapis.com/books/v1/volumes?q=CFk5vep5XWwC

result.component.ts

openDialog(id): void {
    this.apiService.getBooks(id).subscribe((data: {}) => {
        this.booksById = data;
        const dialogRef = this.dialog.open(ResultDialogComponent, {
            width: '500px',
            data: { title: this.booksById.items.volumeInfo.title }
        });

        dialogRef.afterClosed().subscribe(result => {
            console.log('Dialog closed');
        });
    });
}

If I use this, it works! I don't understand why I can't access to items

data: { title: this.booksById.kind }

result-dialog.component.html

<div>
    <h1 mat-dialog-title>Title: {{data.title}}</h1>
    <div mat-dialog-actions>
        <button mat-button (click)="onClick()">Close</button>
    </div>
</div>

Solution

  • this.booksById.items is the array so you need to access it by index

    Try like this

    data: { title: this.booksById.items[0].volumeInfo.title }