When you refresh the page, the number of items in the cart displayed on the navbar always shows 0

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;
  }

  

}

https://i.sstatic.net/GTye7.png

Answer №1

Could it be that the reason for this is due to the ngOnInit method executing the

this.sharedService.removeAllMovieFromCart() 
, resulting in all movies being removed from the cart?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a Singleton Pattern in ReactJS using Context API for Asynchronous Operations

My current implementation involves using a hook: function useFollowUser() { const isFollowing = useRef(false); return (userId) => { if(isFollowing.current) return; // mutual exclusion isFollowing.current = true; ... updat ...

What is the best way to retrieve content from a different website using javascript in an asp.net environment?

Currently working on a web application in asp.net where I want to provide users with a JavaScript code that allows them to fetch content from my website and display it on their own website. To handle user requests on my website, I have implemented a gener ...

Purge the localStorage every time the page is refreshed in Angular 2

After successful authentication, I am storing a token in localStorage. However, every time I refresh the page, I need to delete the token and redirect to a specific router. I'm struggling to find a way to achieve this in Angular, so currently I' ...

jQuery is failing to properly render dynamic content data identifiers

Need help with a dynamic HTML div <a data-id="17" onclick="getcustomer();"> <div class="note note-success"> <h4 class="block">A</h4> <p>Email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Tips for adding a background image using React refs?

Seeking assistance with setting a background for a specific div using react ref, this is my attempted code snippet: The component class structure as follows: import React from 'react'; import PropTypes from 'prop-types'; import class ...

Where could my provider/service have gone missing?

After carefully following the guidelines in the official Angular 2 documentation, I created a CoreModule to handle my services. I also looked into some suggestions on: Providing core singleton services module in Angular 2 Resolving 'No Provider For ...

Exploring the World of GiantBomb APIs

I have successfully created an account and obtained my API key. I am looking to implement a basic search functionality on my webpage, where users can enter a search query and click a button to display the game title and image. You can find more informatio ...

Having trouble accessing object properties fetched via API, receiving the error message "TypeError: Cannot read property '' of undefined" in Next.js with JavaScript

Encountering a unique issue specific to NextJs. Fetching data from an API using a custom hook and receiving an array of objects as the result. Successfully logging the entire result (array of objects). const myMovieGenreObjects = useFetchNavBarCategories( ...

What is the reason behind external JavaScript files being able to access the functions of other external JavaScript files, and what measures can

While I may not be an expert in JavaScript, I find it intriguing that within a project containing 3 JavaScript files, any of these files can access functions from the others. The real puzzle lies in figuring out how to prevent this from happening. For in ...

New project was successfully generated, but the information is missing when transmitted from React to Django API

I recently developed a React + Django application and implemented a basic CRUD feature. Everything was working smoothly until I encountered an issue while creating a project and storing it in the Django database. When I view the project at projects/list, o ...

A sleek and streamlined scrollspy that dynamically updates the active class exclusively for anchor tags

Can anyone help me with this coding problem? I'm currently working on a minimalistic scrollspy code that adds an active class when the content is offset.top. The code works fine, but I want to change the active class to apply to the "a" tag instead of ...

BOOTSTRAP: changing the layout of panels in various sizes for mobile devices

I'm struggling with how to reorganize my panels on mobile devices. Each panel has a different size. Please refer to the attached screenshot for the page layout on large screens (col-lg): https://i.sstatic.net/xcqaT.png EDIT: The layout on large scre ...

Conceal the slider image without removing it

Is there a way to hide the slider background image on mobile screens? @media screen and (max-width: 800px){ .home #mainSliderWrapper { background-image: none; } .stlye { background-image: none; } .img--holder { background-image:none; } } I tr ...

Tips for efficiently utilizing AJAX requests in conjunction with PHP without duplicating code

I have a small script that utilizes AJAX and PHP to showcase an image. As you can see, by calling the mom() function, it searches the PHP file index.php?i=mom and displays the desired image. However, I am looking for a way to streamline the JavaScript cod ...

What is the best way to call a method from app.component in another component?

Having recently delved into Typescript and Angular 2, I've been struggling to find a solution online that fits my needs. Let's consider the example of an app.component: export class AppComponent implements OnInit { constructor(public _test ...

Creating margin on a canvas with jsPDF is a simple task that can be accomplished

Hi there, I'm currently working on generating a PDF from HTML using jsPDF, but I've run into an issue with setting page margins. I would really appreciate any assistance on how to add margins to my pages using the canvas object. Below is the sou ...

Tips on how to efficiently wrap content within a column layout, and to seamlessly shrink it if necessary

I recently encountered an issue where I am attempting to create a three-column layout with each column filled with a dynamic number of divs (boxes) ranging from 5 to 15, each with its own height based on its content. These divs are expected to: 1) Be dis ...

Execute ReactJS function only if query parameters are configured

Provide an Explanation: Within the useEffect, I am retrieving products using the getProducts() function based on the provided data. The data contains search filters that can be updated by the user in real-time. For instance, the data consists of an object ...

align all items centrally and customize Excel columns based on the length of the data

Is there a way to dynamically adjust the column width based on the length of data in an Excel report using PHPexcel? Additionally, how can I center all the data in the Excel sheet? Here is the current code snippet: <?php if (!isset($_POST['send&a ...

Eliminate redundant tags using jQuery

I have a code snippet that I need help with. I want to check for duplicates and if found, display an alert stating that it already exists so users can't insert the same word/tag again. Can someone please assist me? <div id="tags"> <span>a ...