src/app/book-detail/book-detail.component.ts
Component that displays the details of the selected book
selector | app-book-detail |
styleUrls | book-detail.component.css |
templateUrl | ./book-detail.component.html |
constructor(booksService: BooksService, route: ActivatedRoute)
|
Auto-initialize private references in this component to the BooksService instance and the ActivatedRoute instance provided by Angular's dependency injector
Parameters :
|
ngOnInit |
ngOnInit()
|
OnInit lifecycle hook to fetch the book's data right after Angular creates this component See: {@link BooksService#getBook}
Returns :
void
|
book |
book: |
Type : Book
|
Selected book |
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { BooksService } from "app/books.service";
import { Book } from "app/models/book.model";
/**
* Component that displays the details of the selected book
*/
@Component({
selector: 'app-book-detail',
templateUrl: './book-detail.component.html',
styleUrls: ['./book-detail.component.css']
})
export class BookDetailComponent implements OnInit {
/**
* Selected book
*/
book: Book;
/**
* Auto-initialize private references in this component
* to the BooksService instance and the ActivatedRoute instance
* provided by Angular's dependency injector
*
* @param {BooksService} booksService the BooksService instance that Angular will inject
* @param {ActivatedRoute} route the route that led to the loading of this component. Angular will inject this too.
*/
constructor(
private booksService: BooksService,
private route: ActivatedRoute
) { }
/**
* OnInit lifecycle hook to fetch the book's data right after Angular creates this component
*
* See: {@link BooksService#getBook}
*/
ngOnInit() {
// extract the id param from the current route
const bookId: string = this.route.snapshot.params['id'];
// since fetching the book is an async operation, subscribe to the observable
// when the data arrives, the callback will assign it to the book property
this.booksService.getBook(bookId)
.subscribe(book => this.book = book);
}
}
<!-- BACK LINK -->
<a routerLink="/books"><span class="glyphicon glyphicon-arrow-left"></span> All Books</a>
<hr>
<!-- BOOK DETAILS -->
<!-- see here: https://angular.io/api/common/NgIf#showing-an-alternative-template-using-else -->
<!-- book will be undefined till the async call returns with data -->
<div *ngIf="book; else bookUndefined">
<h2 class="h3">{{book.product.title}}</h2>
<div class="row">
<div class="col-sm-2"><img src="assets/no-book-cover.png" alt="cover" class="img-responsive"></div>
<div class="col-sm-10">
<p>by {{book.product.author}}</p>
<book-rating [rating]="book.rating"></book-rating>
<book-price [price]="book.price"></book-price>
<p>{{ book.product.description }}</p>
</div>
</div>
<hr>
<book-comments [comments]="book.comments"></book-comments>
</div>
<ng-template #bookUndefined>Loading book details ...</ng-template>