I've been working on developing a shopping cart feature for an Angular project. I'm trying to define a product as a Product type, but I keep encountering an error message stating: "(product: Product) => { ..."
The error message reads: "No overload matches this call. Overload 1 of 5, '(observer?: PartialObserver | undefined): Subscription', gave the following error. Argument of type '(product: Product) => void' is not assignable to parameter of type 'PartialObserver | undefined'. Property 'complete' is missing in type '(product: Product) => void' but required in type 'CompletionObserver'. Overload 2 of 5, '(next?: ((value: unknown) => void) | undefined, error?: ((error: any) => void) | undefined, complete?: (() => void) | undefined): Subscription', gave the following error. Argument of type '(product: Product) => void' is not assignable to parameter of type '(value: unknown) => void'. Types of parameters 'product' and 'value' are incompatible. Type 'unknown' is not assignable to type 'Product'.ts(2769)
This is the content of my cart.components.ts file:
ngOnInit() {
this.message.getMessage().subscribe((product: Product) => {
this.cartItems.push({
id: 1,
productName: "string",
qty: 1,
price: 1
})
this.cartItems.forEach(item => {
this.cartTotal += (item.qty * item.price)
})
})
My goal is to add the selected product from the array when the "add to cart" button is clicked on the menu page. Instead of having "id: 1, productName: "string"...", I would like to have productName: product.name and productPrice: product.price ...
This is the content of my product.services.ts file:
export class ProductService {
products: Product[] = [
new Product(1, 'Product 1', 'P1 description', 100, 'image1.png'),
new Product(2, 'Product 2', 'P2 description', 300, 'image2.jpg'),
new Product(3, 'Product 3', 'P3 description', 50, 'image3.png'),
new Product(4, 'Product 4', 'P4 description', 20, 'image4.jpg'),
new Product(5, 'Product 5', 'P5 description', 400, 'image5.jpg'),
new Product(6, 'Product 6', 'P6 description', 40, 'image6.jpg'),
]
constructor() { }
getProducts(): Product[] {
return this.products
}
}
Here is the content of my cart-item.components.ts file:
export class CartItemComponent implements OnInit {
@Input() cartItem: any
constructor() { }
ngOnInit() {
}
Finally, here is the content of my Messenger Service file:
export class MessengerService {
subject = new Subject()
constructor() { }
sendMessage(product: Product) {
this.subject.next(product)
}
getMessage() {
return this.subject.asObservable()
}
}