I'm creating a little app which show books from a database. My project looks like this:
| presentational
| ---> book-card
| ---> book-details
| containers
| ---> book-item
| ---> books
| services
| ---> books
I use BookItemComponent as a container, this class communicates with BooksComponent.
Books components show the books card (like bootstrap style), books-card component has input (get the book infos) and output (to show more actions and details about the book).
Here is the code for these classes :
book-item.component.ts :
export class BookItemComponent implements OnInit {
book: Book; /*= {"title": "New harry", "author": "J.K Rowling"};*/
constructor(private booksService: BooksService, private route: ActivatedRoute) { }
ngOnInit() {
console.log("BookItemComponent.ngOnInit()");
this.booksService.getBooks().subscribe(
(books) => {
const param = this.route.snapshot.params.id;
console.log(param);
this.book = books.find(book => book.id == param);
});
}
}
book-item.component.html :
<p>Book-item</p>
<p *ngIf="!book">No book found..</p>
<app-book-details
[book]="book"
(addToFav)="onAddToFav(book)"></app-book-details>
The class BookItemComponent communicates with BooksComponent which is the main container :
books.component.ts
export class BooksComponent implements OnInit {
books: Book[];
constructor(private booksService: BooksService, private router: Router) { }
ngOnInit() {
this.booksService.getBooks().subscribe(books => {
this.books = books;
});
}
onShowDetails(event: Book) {
this.router.navigate(['/', event.id]);
}
}
And finally :
book-card.component.ts :
@Component({
selector: 'app-book-card',
templateUrl: './book-card.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrls: ['./book-card.component.css']
})
export class BookCardComponent {
@Input() book: Book;
@Output() showDetails = new EventEmitter<Book>();
showBookDetails(event: Book) {
if(event) {
this.showDetails.emit(event);
}
}
}
** PROBLEM ** : In the method BookItemComponent.ngOnInit(), when I use this :
this.booksService.getBooks().subscribe(
(books) => {
const param = this.route.snapshot.params.id;
this.book = books.find(book => book.id == param);
});
I can see that book is undefined, look at this picture: