Angular Add Property To JSON Object From Input Using Api

Viewed 55

Hello my goal is to add a input value to the object property.

The way it stands is that the customer wants to add an item to his or her shopping cart, but before the item is added they must choose the size. I have the form as well as the validation working I'm able to get the value when radio button is clicked and calls the onSubmit() function. I already have a cart service function in place to add to cart which is working using an api,. I am able to get the id of the post item. I need to get that Valuesize and add it as property (size:Valuesize) which is a string.

I do pass in the Valuesize as a parameter to the cartservice. Thinking logically I need to do an update in order to add the object property. This is were I get stuck. I did attempt to add the functionality for this but it does not behave as expected. I would appreciate if someone could point me in the right direction it would be greatly appreciate it.

code snippet below

Model

My model has the size as optional there fore it does not exist on the object. I'm not sure if I should do a post first then a get request by id and add the property in.

import { Product } from './product';


export class CartItem {

    static splice(arg0: number) {
      throw new Error('Method not implemented.');
    }

    id: number;
    productId: number;
    productName: string;
    qty: number;
    price: number;
    size?:string;
    imageUrl:string;

    constructor(id:number, size:string,  product:Product, qty= 1) {

        this.id = id;
        this.productId = product.id;
        this.price = product.price;
        this.size = size;
        this.productName = product.name;
        this.qty = qty;
        this.imageUrl = product.imageUrl;
         
        
    }


    
}

productlist.ts

export class ProductItemComponent implements OnInit {

  form: FormGroup; 
  submitted=false;
  sizeBy:string;

  Valuesize:string;
 


  
 @Input() productItem:Product 


 @Input() addedToWishlist: boolean;


 //@Input() addedToWishlistitem: boolean = false;

  constructor(private msg: MessengerService, private cartService: CartService,  private formBuilder: FormBuilder,
    private wishlistService:WishlistService, private _wishlistitemService: WishlistItemService,private alertService: AlertService, private _data:AppserviceService) { }


    //: void  hold this for now on ngOnInit
  ngOnInit() {
    this.form = this.formBuilder.group({
        sizeBy: ['', Validators.required]
    });
       
    
    }




 // convenience getter for easy access to form fields
 get f() { return this.form.controls; }

 onSubmit() {

    this.submitted = true;
  
   // reset alerts on submit
   this.alertService.clear();
    
   // stop here if form is invalid

   if (this.form.invalid) {
        return;
   } 

   if (!this.form.invalid){
      this.Valuesize = this.form.value.sizeBy
            
       this.handleAddToCart();
     }
  
  }

 
  handleAddToCart(){
    this.Valuesize;
    alert("Am I able to to get Valuesize" + this.Valuesize)

 this.cartService.addProductToCart(this.productItem,this.Valuesize)
 .subscribe((product:Product) =>{
      this.productItem = product;
       this.msg.sendMsg(this.productItem)
  })
}

}

cartservice

addProductToCart(product:Product,Valuesize):Observable<any>{
    //return this.http.post(cartUrl, {product});
    
    alert("Inside add product to cart");
     return this.http.post<any>(cartUrl, {product}).pipe(
      map(data =>{
       alert("To this point");
         this.postId=data.id;  //able to get id of item of post
           console.log("Logging"+ data);
           console.log("Get Id from a post"+ this.postId)
           alert("what is the item size" + Valuesize)
       
         /*Need to update data */
         let id = this.postId;
         let endPoints = "/cart/";
         this.http.put(this.url + endPoints + id, 
          this.newObjectProp).pipe(
          map((option: any[]) => {
            //new property to be added
              this.newObjectProp={
              size:Valuesize
             };
             //assign new property and return
             console.log("Getting Item from cart" + option); 
            return Object.assign(option,this.newObjectProp)
          
         })
         )
         
         return data;
     
  
     })

     )
  
   }

The way it appears on json server db.json

"cart": [
 {
      "product": {
        "id": 4,
        "name": "Purple Outfit",
        "description": "Lorem Ipsum is simply 
         dummy text of the printing and 
         typesetting industry. Lorem Ipsum has 
         been the industry's standard dummy 
         text ever since the 1500s, when an 
         unknown printer took a galley of type 
         and scrambled it to make a type 
         specimen book.",        
        "imageUrl":"http://localhost:4200/
         assets/purpleoutfit4.png",
        "price": 100
      },
      "id": 7
    }

    
  ],
1 Answers

The Object.assign will never work for what I'm trying to achieve because object assign copies all enumerable own properties from one or more source objects to a target object. The put will never work either. There is far to much unnecessary code. I took all that out and started back with

addProductToCart(product:Product,Valuesize:string):Observable<any>{


return this.http.post<any>(cartUrl, {product})
   

}

Any code needed to add the Valuesize will have to go before the return.

Related