简体   繁体   中英

How to add data in a method in Typescript using interface?

I am working on a shopping cart quiz and while clicking on add button the product details are passed from child to parent using event emitter and to the component but I am not able to understand how to add it to cart? it is showing error in addproduct method below because of properties not matching in product and cart interfaces

addproduct(product: Product){this.cart.items.push(product)}

throws error: (parameter) product: Product Argument of type 'Product' is not assignable to parameter of type 'CartItem'. Type 'Product' is missing the following properties from type 'CartItem': item, quantityts(2345)

 export class AppComponent {
   products: Product[];
   cart: Cart;

constructor() {
     this.cart = {
     items: []
    } as Cart
 } 

   ngOnInit() {
this.products = [...PRODUCTS].map((product, index) => {
  product.id = index + 1;
  product.image = `/assets/images/items/${product.name.toLocaleLowerCase()}.png`;
  product.cartQuantity = 0;
  return product;
});   
    
 addToCart(product: Product) {
    this.cart.items.push(product); 
   }


**cart.ts**

export interface CartItem {
  id: number;
  item: string;
 quantity: number;
 }
export interface Cart {
  items: CartItem[];
 }

**Product.ts**

 export interface Product {
    name: string;
    price: number;
    id?: number;
    image?: string;
    cartQuantity?: number;
  }
  export enum UpdateMode {
     SUBTRACT,
    ADD
  }

app.component.html

 <app-product-list [products]="products"
                (onAddToCart)="addToCart($event)"
                (onQuantityUpdate)="updateCart($event)"
                class="flex-70"></app-product-list>
 <app-cart class="flex-30" [cart]="cart"></app-cart>

How do i send the product to input property in cart.component.ts file

 export class CartComponent implements OnInit{
    @Input() cart: Cart;
       constructor() {}

Hi the error is because you are trying to assign a product of type Product to type Cart. Both have different keys inside and all are mandatory. On first look, you can refactor it like this and it should work.

    addToCart({id, name, cartQuantity}: Product) {
     let cart: CartItem = {
       id,
       item: name,
       quantity: cartQuantity
     };

    this.cart.items.push(cart); 
    console.log(this.cart)
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM