user14065257
user14065257

Reputation: 63

Angular can access to object but cannot read property

I have followed setup which gets pages from parent component and loads it as *ngFor correctly, but once I use function to get related book name by {{ getBookName(id) }}, even though it returns the book object, can not find its properties like book.name and returns TypeError: Cannot read property 'name' of undefined


import { Component, OnInit, EventEmitter, Input };
import { Store } from '@ngrx/store';
import { AppStore } from '../shared/store.interface';
import * as BookSelectors from '../shared/book/book.selector';

@Component({
    selector: 'app-pages',
    template: `'
        <button *ngFor="let page of pages">
            page {{ page.number }} in {{ getBookName(page.book_id) }} <!-- page 32 in Book A -->
        </button>'`,
    styles: ['button{ border: 1px solid red }']
})
export class PagesComponent {

   @Input() pages: any[] = []; // comes from parent component

    constructor(private store$: Store<AppStore>) {}

    getBookName(id: number) {
        console.log(id) // 1
        this.store$.select(BookSelectors.selectBookById, id).subscribe(
            book => {
                console.log(book) // {id: 1, name: 'Book A', author: 'author A'} 
                return book.name // TypeError: Cannot read property 'name' of undefined
            }
        )
    }

}

Upvotes: 0

Views: 1101

Answers (2)

jcobo1
jcobo1

Reputation: 1180

Try using the async pipe: | async

With the asynchronous pipe you’re indicating to the view that the value comes from a promise and the value may not be available when rendering the view.

Another approach could be using ? before the attribute like object?.attribute

Upvotes: 0

waseemrakab
waseemrakab

Reputation: 312

What you’re trying to do is not valid. you’re trying to subscribe from the template and getting the value immediately, which will not work async/observable way. you should instead use the async pipe by angular instead. Like this.

getBookName(id: number) {
  return this.store$.select(BookSelectors.selectBookById, id).pipe(
    map((book) => {
      return book.name;
    })
  );

and in the template just use it like this

<button *ngFor="let page of pages">
  <div *ngIf="getBookName(page.book_id) | async as pageName">
    page {{ pageName }}
  </div>
</button>

Upvotes: 2

Related Questions