When using my angular application, I encountered a problem with adding movies to a cart. Although I can successfully add them to the cart and see the correct number of movies reflected in the navbar, upon refreshing the page, the count resets to 0.
Here is the HTML code for displaying the count:
<li *ngIf="signedIn" class="nav-item" routerLinkActive="active">
<a class="nav-link" [routerLink]="['/cart',authService.decodedToken.nameid]">Cart <span class="badge badge-dark">{{cartItemCount}}</span></a>
</li>
Below is my shared service responsible for updating the cart:
export class SharedcartService {
private currentCartCount = new BehaviorSubject(0);
currentMessage = this.currentCartCount.asObservable();
constructor() {
}
addMovieToCart(movie: any) {
sessionStorage.setItem('movie', JSON.stringify(movie));
}
getMovieFromCart() {
return JSON.parse(sessionStorage.getItem('movie'));
}
removeAllMovieFromCart() {
return sessionStorage.removeItem('movie');
}
updateCartCount(count: number) {
this.currentCartCount.next(count);
}
}
Here is a snippet from my cart.ts file:
export class CartComponent implements OnInit {
user: User;
defaultQuantity: number = 1;
movieAddedTocart: any;
allTotal: number;
constructor(private http:HttpClient, private userService: UserService,private sharedService: SharedcartService,
private alertify: AlertifyService,private route: ActivatedRoute ) { }
ngOnInit() {
this.route.data.subscribe(data=>{
this.user=data['user'];
});
this.movieAddedTocart=this.sharedService.getMovieFromCart();
for (let i in this.movieAddedTocart) {
this.movieAddedTocart[i].Quantity = 1;
}
this.sharedService.removeAllMovieFromCart();
this.sharedService.addMovieToCart(this.movieAddedTocart);
this.calculteAllTotal(this.movieAddedTocart);
}
onRemoveQuantity(movie: any)
{
this.movieAddedTocart=this.sharedService.getMovieFromCart();
this.movieAddedTocart.find(p=>p.aMovieId == movie.aMovieId).Quantity = movie.Quantity-1;
this.sharedService.removeAllMovieFromCart();
this.sharedService.addMovieToCart(this.movieAddedTocart);
this.calculteAllTotal(this.movieAddedTocart);
}
calculteAllTotal(allItems:any)
{
let total = 0;
for (let i in allItems) {
total= total+(allItems[i].Quantity *allItems[i].aPrice);
}
this.allTotal=total;
}
}