I'm trying to select on book from a list of books returned in a search using the google books api. When I select a book, I want to get the id through the route params and display more details of the selected book to the right.
I already know how to get the id through the route params, but displaying the details of the book after I select it is now the problem.
How do I go about this?
book-search.component.html
<div class="row">
<div class="col-xs-12">
<form (ngSubmit)="onSearch(f)" #f="ngForm">
<div class="input-group-append">
<input
type="search"
class="form-control"
placeholder="Search for books"
id="search"
name="search"
ngModel
/>
<button class="btn btn-outline-primary" type="submit">Search</button>
</div>
</form>
</div>
</div>
<br />
<div *ngIf="isLoading" style="padding-left: 70px;">
<app-loading-spinner></app-loading-spinner>
</div>
<div class="row">
<div *ngIf="books && !isLoading">
<div class="col-xs-12">
<div
[routerLink]="['/books', book.id]"
routerLinkActive="active"
style="cursor: pointer;"
*ngFor="let book of books"
>
<img
src="{{ book.volumeInfo.imageLinks.thumbnail }}"
alt="{{ book.volumeInfo.title }}"
style="max-height: 50px;"
/>
{{ book.volumeInfo.title }}
</div>
</div>
</div>
<div>
<router-outlet></router-outlet>
</div>
</div>
book-search.component.ts
import { Component, OnInit } from "@angular/core";
import { BookSearchService } from "./book-search.service";
import { NgForm } from "@angular/forms";
@Component({
selector: "app-book-search",
templateUrl: "./book-search.component.html",
styleUrls: ["./book-search.component.css"]
})
export class BookSearchComponent implements OnInit {
books: [];
isLoading = false;
constructor(private bookSearchService: BookSearchService) {}
ngOnInit() {}
onSearch(form: NgForm) {
this.isLoading = true;
const value = form.value.search;
this.bookSearchService.searchBooks(value).subscribe(resData => {
this.books = resData.items;
console.log(resData);
this.isLoading = false;
});
}
}
book-search-detail.component.ts
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params } from "@angular/router";
@Component({
selector: "app-book-search-detail",
templateUrl: "./book-search-detail.component.html",
styleUrls: ["./book-search-detail.component.css"]
})
export class BookSearchDetailComponent implements OnInit {
id: any;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.id = params["id"];
console.log(this.id);
});
}
}
Since you pass the book-id to the detail-component, you can fetch the corresponding entity details based on the id in the ngOnInit
method.
Thereby, you avoid (and don't) need to pass in the actual entity itself.