I'm currently working on a shopping app and trying to implement a feature where clicking on a product adds it to the checkoutList
. However, I'm facing an issue where when a product is clicked, no data is being sent and I am getting 'undefined' back. I have created a service called messenger.service.ts which includes the following function triggered by the button:
export class MessengerService {
subject = new Subject()
constructor() {}
sendMsg(product) {
console.log(product)
this.subject.next(product) // triggering an event
}
getMsg() {
return this.subject.asObservable()
}
}
Here is the component that displays the products that can be added to the checkoutList
:
export class ProductListComponent implements OnInit {
productList: Product[] = [];
@Input() productItem: Product;
constructor(private productService: ProductService, private msg: MessengerService) {}
ngOnInit(): void {
this.productList = this.productService.getProducts();
}
onAddToCheckoutList() {
this.msg.sendMsg(this.productItem);
}
}
The component that listens to the service:
<div class="col-3" *ngFor="let product of productList">
<a href="#" class="list-group-item clearfix" [productItem]="product" (click)="onAddToCheckoutList()">
<span class="pull-left">
<img
style ="height: 72px;"
[src]="product.imagePath"
alt="{{ product.name }}" >
</span>
<div class="productName">
<p> <b> {{product.name}} </b> <br> Price: €{{product.price}}</p>
</div>
</a>
</div>
To provide a visual representation of the application, here is a screenshot: