Nikson
Nikson

Reputation: 940

Angular4 - new product count(quantity) is not add with previous count

I am working in an e-commerce website,In this I have some quantity of products in my cart when I add more products the new quantity is not added with the previous count. In my case it always replace the old cart value with new cart value..

This is my service component

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class CartdataService {

  private Count = new BehaviorSubject<number>(0);
  cast = this.Count.asObservable();

  constructor() { }

  editCount(newCount){
  this.Count.next(newCount);
  }

}

This is my app component (here I display the total cart value in top of the page)

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DatePipe } from '@angular/common';
import { HostListener } from '@angular/core';
import {CartdataService} from './cartdata.service';


@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']

})

export class AppComponent implements OnInit{
 nCount : number;
  constructor(private CartdataService:CartdataService,private http: HttpClient) { }
 ngOnInit() {
        this.CartdataService.cast.subscribe(totalItems=> this.nCount = totalItems);
}
}

App component HTML

<span class='notification-counter badge badge-danger' [class.disabled]="nCount == 0" data-toggle="modal" data-target="#exampleModal">{{nCount}}</span>

This is my Add to cart screen HTML(Here adding the product quantity of the selected product )

<div class="col-sm-9">
              <div class="row">
                <div class="col-sm-3">
                    <input type="text" readonly  class="form-control col-8 text-center bg-white font-weight-bold " id="counterval" value="{{counter}}" #Totalcartval>
                </div>         
                    <a class="btn btn-primary text-white" (click)="decrement()" role="button">
                        <i class="fa fa-minus" style="font-size:15px"></i>
                    </a>
                    <div class="col-sm-1"></div>
                    <a class="btn btn-primary text-white" (click)="increment()"  role="button">
                        <i class="fa fa-plus" style="font-size:15px"></i>
                    </a>            
            </div>
          </div>


 <button type="button"  (click)="sendRecord(Totalcartval.value)" class="btn btn-success" data-toggle="modal" data-target=".bd-example-modal-lg">Add To Cart</button>  

by clicking on the plus and minus buttons I can increase and decrease the quantity then I clicked on the ADD TO CART button the selected quantity is passed to the service file and database

This is my-cart component

import { Component,EventEmitter,Output } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { SessionStorageService,SessionStorage } from 'angular-web-storage';
import {CartdataService} from '../cartdata.service';


@Component({
  selector: 'app-my-cart',
  templateUrl: './my-cart.component.html',
  styleUrls: ['./my-cart.component.css'],
  outputs :['ChildEvent']
})

export class MyCartComponent  {
  today = Date.now();
  fixedTimezone =this.today;
  public counter : number = 1;   
  res : string;
  public Count : number;


  imageURL:string ="assets/Product _Details/Show1.png";

    increment(){this.counter += 1;}
    decrement(){if(this.counter >1){this.counter -= 1;}}

    public sendRecord(Totalcartval : number ) {  
      this.CartdataService.editCount(Totalcartval);
      this.http.get('http://freegeoip.net/json/?callback')
                 .subscribe(
                    data => this.saveIP(data['ip'],Totalcartval),
                    error => console.error(error)
                 );
    }
    saveIP(address: string,cartval :number) {
      this.http.get(`http://localhost:57036/api/data/CartCount/?IP_ADDRESS=${address}&ITEM_QTY=${cartval}&TIME=${this.fixedTimezone}`)
               .subscribe(data => this.res  = (data['ITEM_QTY']),
               error => console.error(error));       
  } 
 ngOnInit() {}

}

Here I can't add the previously selected product's quantity with newly selected product's quantity .Help me to fix this issue. Thanks.

Upvotes: 2

Views: 1721

Answers (1)

rmcsharry
rmcsharry

Reputation: 5552

You code has a few problems, so rather than point them out I added your code to stackblitz and fixed them.

See it here.

The first major problem was this:

public sendRecord(Totalcartval : number ) {
  this.CartdataService.editCount(Totalcartval);
...

which I changed to this:

public sendRecord() {  
  this._cartDataService.editCount(this.counter);
...

#Totalcartval will be passed from the template as a string. There is no need for this template variable, since you already have the count stored in this.counter so easier to just use that.

The other major problem was identified in the comments by @David - you were always passing the NEW TOTAL and not keep tracking of the existing (previous) total. That was fixed by changing the service as per David's suggestion:

  editCount(newCount: number){
    this.currentCount += newCount; 
    this.Count.next(this.currentCount);
  }

FYI I could not get font-awesome to load in stackblitz, so just replaced the icons with + and -

Upvotes: 2

Related Questions