Search code examples
angularobservablengrxngrx-store

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
            }
        )
    }

}

Solution

  • 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>