Angular's NgShoppingCart is designed in such a way that items stored in the localStorage are automatically cleared out

I am currently working on an Angular project using version 8.0.0.

To integrate a shopping cart feature into my Angular project, I decided to incorporate the NgShoppingCart library by following the instructions provided here.

After adding the library in my app.module, as per the guidelines, I proceeded to add the following code snippet in one of my components:

 constructor(private cartService: CartService<TourCartItem>) {
  }

  ngOnInit() {
  }

  add() {
    const item = new TourCartItem({id: 1, name: 'My item'});
    item.setId(9);
    item.setName('Test item');
    item.setPrice(10);
    item.setQuantity(10);
    this.cartService.addItem(item);
  }

Upon adding an item, everything functions correctly, and I can see the item stored in localStorage.

However, upon reloading the page, all items are reset, which leads me to suspect that there might be an issue with the implementation.

Below is a snippet from my app.module:

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    SharedModule.forRoot(),
    ShoppingCartModule.forRoot({
      itemType: TourCartItem,
      serviceType: 'localStorage',
      serviceOptions: {storageKey: 'ToursCart', clearOnError: true},
    }),
    CoreModule,
    ServiceWorkerModule.register('/ngsw-worker.js', {enabled: environment.production}),
  ],
  providers: [],
  bootstrap: [CoreComponent]
})
export class AppModule {
  constructor() {
    if (!environment.production) {
      console.log('app');
    }
  }
}

The code for my custom class TourCartItem is shown below:

export class TourCartItem extends CartItem {
  
  // Class definition here
  
}

If anyone has experience with installing and troubleshooting this particular library, your assistance would be greatly appreciated. Thank you in advance.

Answer №1

After resolving the issue, I discovered that the problem stemmed from my custom ItemCart lacking a proper fromJSON implementation.

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

Update the src attribute of img elements using regular expressions

Figured it out in case anyone might find it useful, here's the solution: var feed = feeds.entries[i].content; var parsedFeed = feed.replace(/src=/gi, "tempsrc="); var tmpHolder = document.createElement('div'); tmpHolder.innerH ...

When trying to establish Expo cli through npm install, the process gets stuck specifically during the extraction phase of

My attempt to install Expo for React Native using npm install -g expo-cli has been unsuccessful as the installation process pauses indefinitely at extract:rxjs: still extract <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d7d ...

Bootstrapping Angular2 asynchronously using an external JSON configuration file

After upgrading to angular2 RC6, I am facing a challenge in loading an external JSON config file before bootstrapping my AppModule. It was working fine with RC5 but now I am struggling to find the equivalent way of injecting this data. /** Create dummy XS ...

Unable to append item to document object model

Within my component, I have a snippet of code: isLoaded($event) { console.log($event); this.visible = $event; console.log(this.visible); this.onClick(); } onClick() { this.listImage = this.imageService.getImage(); let span = docu ...

Refreshing rows in ngx-datatable

Just started using ngx-datatable (version 11) with Angular-5 and encountered an issue. When loading rows during ngInit, everything works fine. However, when lazy-loading due to a user search request, the table shows the correct total number of rows but onl ...

Achieve the central element while scrolling on the window

What am I doing wrong? I've been attempting to target the #second element on scroll Here is an example with console.log CODEPEN EXAMPLE $(window).scroll(function(){ var section = $("#second").offset().left, scrollXpos = $( ...

Updating the resolved path in the Vue configuration

Is it possible to change the file directory of .vuerc? My Vue installation is done through npm. When I use vue config, the current path is /home/username/.vuerc, but I'd like it to be something along the lines of /home/username/.config/vue/vuerc. Is t ...

Communicating data transfer between two Node.js servers through the use of the Node Serial Port technology

How can I send the message "Hello world" from one nodejs server to another using node-serialport? I have confirmed that the radios connecting the two servers are properly connected as they are displaying buffer information after running my current code. ...

Express.js - display the complete information

Trying to display an array of objects (highcharts points) is giving me some trouble. Instead of the actual data, I'm seeing [object Object]. It seems that JSON.stringify() doesn't play well with HTML. util.inspect also doesn't work as expe ...

JavaScript encounters an error when trying to create a MarkLogic instance with an array

[javascript] XDMP-CAST: (err:FORG0001) xs:string#1(.) -- Invalid cast: `json:object(<json:object xmlns:xs="http://www.w3.org/2001/XMLSchema" ` xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>) cast as xs:string Stack Tr ...

Leveraging Javascript/jquery to retrieve image data for a specific frame within a video

Query My aim is to optimize the code for image manipulation on a web browser using JavaScript. One possible solution I am considering is utilizing a video file to reduce HTTP requests. Is there a way to extract a single frame from a video in png, jpg, or ...

Retrieve data from AJAX once the cycle is complete

Currently, I am attempting to calculate the sum of results from an external API by making a single request for each keyword I possess. The code is functioning properly; however, the function returns the value before all the ajax requests are completed. Eve ...

Is it possible to execute a function when the AJAX request is successful and returns a status code of

I am looking to implement the success function to only run a certain function if the status code is 200. I have come across this example: $.ajax ({ success: function(data,textStatus,jqXHR){ external(); } )}; However, I have not found a clear ...

Is there a different method similar to Textfield onChange that works like the HTML onChange attribute?

In my current setup, I have a Textfield component nested within other components where I pass a function pointer down to it as a prop. The challenge I'm facing is that the function responsible for passing the contents of the Textfield back up to the r ...

AngularJS allows for the passing of a function value into another function

Is there a way for me to pass a value from one function to another? Here is an example of what I am trying to achieve: HTML <div> <li ng-repeat="language in languages" ng-click="myFirstFunction(firstValue) {{lang ...

Fetching data dynamically from the server using AJAX for a interactive chart with Flot

After looking at the Flot reference, they mentioned, The plot function can also be used as a jQuery chainable property. Is it possible to configure the Flot chart in this way? var pid = ''; var kid = ''; var chartasset; $(documen ...

What could be causing the 500 response code when making a request to the NextJS API route within the app directory?

Every time I attempt to access my API route, a 500 Internal Server Error code is returned The origin of the request export const fetchSuggestion = async () => { const response = await fetch('/api/getSuggestion', { cache: 'no-store&ap ...

The medium-zoom feature is currently experiencing issues with functionality within Angular version 13

I've been attempting to incorporate medium-zoom functionality into my project using https://www.npmjs.com/package/medium-zoom Here are the steps I took: ng new medium_zoom_test (Angular 13) with routing & css npm install medium-zoom The image is ...

What is the best way to include a title and a close button at the top of a menu, before the first item, when a button menu is clicked in material-ui?

One of the challenges I'm facing is adding a title to an icon button menu that contains a checkbox list of menu items. When the user clicks on the icon and opens the dropdown, I want the title to appear at the top of the dropdown along with a close bu ...

Designing a mobile user interface for time intervals

Currently, I am utilizing a datetimepicker for inputting a duration of time within a form. While the UI functions smoothly on a desktop, it struggles in a mobile setting. Despite my efforts, I have yet to discover a suitable alternative that seamlessly ope ...