Why am I unable to display the data from the main component in the payment component?
Solution
export class BookListService {
url: string = 'http://henri-potier.xebia.fr/books';
item:any=[];
public book: Book[];
constructor(private http: HttpClient) { }
getBookList(): Observable<Book[]> {
return this.http.get<Book[]>(this.url);
}
addToBook() {
this.item.push(this.book);
}
}
payment.component.ts
export class PaymentComponent implements OnInit {
public book: Book;
addedBook: any = [];
constructor(private bookListService: BookListService) { }
ngOnInit(): void {
this.addedBook = this.bookListService.getBookList();
}
}
payment.html
<div *ngFor="let book of addedBook">
<span>{{ book.title }}</span>
<span>{{ book.price | currency }}</span>
</div>
main.component.ts
export class MainComponent implements OnInit {
bookList: any = [];
constructor(private bookListService: BookListService) { }
ngOnInit(): void {
this.bookListService.getBookList().subscribe(data => {
this.bookList = data
})
}
addButton() {
this.bookListService.addToBook()
alert('item added');
}
}
main.component.html
<div class="grid-container">
<div class="wrapper" *ngFor="let book of bookList" class="form-group">
<div class="product-img">
<img [src]="book.cover" alt="livre" height="420" width="327">
</div>
<div class="product-info">
<div class="product-text">
<h2>{{book.title}}</h2>
<p>{{book.synopsis}}</p>
</div>
<div class="product-price-btn">
<p>{{book.price | currency: 'EUR'}}</p>
<button type="button" (click)="addButton()">buy now</button>
</div>
</div>
</div>
</div>
interface
export interface Book {
title: string;
price: number;
cover:string;
synopsis:string;
}