[英]Angular Shopping Cart - Local Storage Service and subscribing to changes
我在解決使用購物車服務通過本地存儲監控購物車更改的問題時遇到了很多麻煩。 如何訂閱添加數量或刪除項目等所做的更改,以便頁面在事件發生時顯示新數據?
當我的其他方法對 localStorage 進行更改時,有沒有辦法持續監控 localStorage 並更新我的 getItems()?
我整天都在忙這件事,有點慢,任何幫助都很棒!
CartComponent.ts ---
import { Component, OnInit } from '@angular/core';
import { CartService } from '../services/cart.service';
import { Products } from '../models/products';
import { Item } from '../models/item';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
product: Products;
public items: Item = new Item();
item;
constructor(private cartService: CartService) { }
ngOnInit(): void {
this.items = this.cartService.getItems();
//this.items = this.cartService.getItems();
}
deleteItem(item){
this.cartService.deleteItem(item);
let domItem = document.getElementById(`cart-item`+item.product.id);
setTimeout(() =>{
domItem.classList.add('delete-style');
domItem.parentNode.removeChild(domItem);
},1000);
}
addQty(item){
this.cartService.addQty(item);
}
}
購物車服務.ts ---
import { Injectable } from '@angular/core';
import { Products } from '../models/products';
import { Item } from '../models/item';
import { Observable, of } from 'rxjs';
import { StorageService } from '../services/storage.service';
let itemsInCart = [];
let cart = [];
//console.log("itemsInCart: ", itemsInCart);
@Injectable({
providedIn: 'root'
})
export class CartService {
product: Products;
items: Item;
constructor() { }
addToCart(product: Products) {
let local_storage;
let itemsInCart = []
this.items = {
product: product,
quantity: 1,
}
if(localStorage.getItem('cart') == null){
local_storage =[];
console.log("LOCALSTORAGE NULL",JSON.parse(localStorage.getItem('cart')));
itemsInCart.push(this.items);
localStorage.setItem('cart', JSON.stringify(itemsInCart));
console.log('Pushed first Item: ', itemsInCart);
}
else
{
local_storage = JSON.parse(localStorage.getItem('cart'));
console.log("LOCAL STORAGE HAS ITEMS",JSON.parse(localStorage.getItem('cart')));
for(var i in local_storage)
{
console.log(local_storage[i].product.id);
if(this.items.product.id == local_storage[i].product.id)
{
local_storage[i].quantity += 1;
console.log("Quantity for "+i+" : "+ local_storage[i].quantity);
console.log('same product! index is ', i);
this.items=null;
break;
}
}
if(this.items){
itemsInCart.push(this.items);
}
local_storage.forEach(function (item){
itemsInCart.push(item);
})
localStorage.setItem('cart', JSON.stringify(itemsInCart));
}
}
getItems(){
console.log("Cart: ", JSON.parse(localStorage.getItem('cart')));
return this.items = JSON.parse(localStorage.getItem('cart'));
//return this.items =
}
deleteItem(item){
item = item;
console.log("Deleting : ",item);
let shopping_cart;
let index;
shopping_cart = JSON.parse(localStorage.getItem('cart'));
for(let i in shopping_cart){
if (item.product.name == shopping_cart[i].product.name)
{
index = i;
console.log(index);
}
}
shopping_cart.splice(index, 1);
console.log("shopping_cart ", shopping_cart);
localStorage.setItem('cart', JSON.stringify(shopping_cart));
}
addQty(item: Item)
{
item = item;
let shopping_cart;
shopping_cart = JSON.parse(localStorage.getItem('cart'));
for(let i in shopping_cart){
if(item.product.name == shopping_cart[i].product.name){
shopping_cart[i].quantity +=1;
item = null;
break;
}
}
localStorage.setItem('cart', JSON.stringify(shopping_cart));
}
numberOfItems(){
let itemsInCart = JSON.parse(localStorage.getItem('cart'));
return itemsInCart.length;
}
clearCart(){
localStorage.clear();
}
}
您可以為此使用 rxjs 主題:
在您的服務中:
subject = new Subject<any>();
當您更新存儲在localStorage
中的值時,請使用.next
例子:
localStorage.setItem('cart', JSON.stringify(itemsInCart));
subject.next('changed');
並在您的組件中訂閱它,您可以在生命周期掛鈎中訂閱:
ngOnInit() {
this.cartService.subscribe((status) => {
//..you will reach here when you use `.next` because this callback function gets
// executed
this.items = this.cartService.getItems();
})
}
根據MDN有一個你可以收聽的事件
window.addEventListener('storage', function(e) {
document.querySelector('.my-key').textContent = e.key;
document.querySelector('.my-old').textContent = e.oldValue;
document.querySelector('.my-new').textContent = e.newValue;
document.querySelector('.my-url').textContent = e.url;
document.querySelector('.my-storage').textContent = JSON.stringify(e.storageArea);
});
但如果我是你,我會跟蹤 singleton 服務https://angular.io/guide/singleton-services中的項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.