It would appear that the onSubmit function below is saving to localStorage but I deployed the code to the Web and when I refreshed the page, the shopping cart got emptied. I can't test the code after every modification because I'm in development mode and the page re-compiles when it's refreshed but I can test it with the deleteItem function which uses splice. Splice only works on an array and when I click the delete button, the product gets cleared so that tells me it's not using localStorage.
In the component:
- items = [];
-
- public onSubmit(thumbnail, quantity, product_name, product_price){
-
- const data = {
- thumbnail,
- quantity,
- product_name,
- product_price
- };
-
- localStorage.setItem('items', JSON.stringify(data));
- this.items.push(JSON.parse(localStorage.getItem('items')));
- this.isSubmitted = true;
- }
-
- deleteItem(i){
- this.items.splice(i,1);
-
- }
In the HTML:
- <tr *ngFor="let item of items; let i = index">
- <td>
- <button type="button" (click)="deleteItem(i)">X</button></td>
- <td><img src="{{item.thumbnail}}" /></td>
- <td>{{item.quantity}} </td>
- <td>{{item.product_name }} </td>
- <td>{{item.product_price }} </td>
- <td>{{item.quantity * item.product_price }}</td>
- </tr>