typescript 使用Angular的本地存储

ippsafx7  于 2023-04-13  发布在  TypeScript
关注(0)|答案(2)|浏览(127)

我正在开发一个电子商务,我试图设置本地存储来保存购物车内的元素。
所有的罚款,当我添加一个产品到购物车和所有,但一旦我刷新购物车页面,所有的产品就消失了。
我试着设置本地存储,我不知道我错在哪里...
我的浏览器可以使用本地存储权限(Edge)。
cart.component.ts:

export class CartComponent {

  products = this.cartService.getProducts();

  constructor(
    private cartService: CartService
  ) { }

  totalPrice = this.cartService.getProducts().reduce((acc, product) => acc + product.PriceWithIVA, 0);



}

cart.service.ts:

addToCart(product: ProductDTO) {
    this.products.push(product);

    let products = [];

    if (localStorage.getItem ('products')) {
        products = JSON.parse(localStorage.getItem('products'));
    }

    products.push ({
        name: product.Name,
        image: product.Attachment,
        price: product.PriceWithIVA
    })

    localStorage.setItem ('products', JSON.stringify(products));
    this.products = products;
}



getCartDetailsByUser() {
    const data = JSON.parse(localStorage.getItem ('products'));
    this.products = data;

    if (data !== null) {
        this.cartQuantity = data.length;
    }
}

getProducts() {
    return this.products;
}

clearCart() {
    localStorage.removeItem ('products');
    this.products = [];
    this.cartQuantity = 0;
}
pcww981p

pcww981p1#

在服务的构造函数中,应询问“localStorage.getItem('products')”

constructor(){
   const products=localStorage.getItem ('products')
   this.products=products?JSON.parse(products):[];
}

更新*@Jany,您需要注意变量的名称-您将数据存储为name,price和image,但当您添加到购物车时收到的对象具有但收到Name,Attachment和PriceWithIVA。

此外,您有可变的产品在服务和在您的卡,也许这是很好的使用吸气剂。
我分叉了你的代码

export class CartComponent implements OnInit {

  totalPrice: number;

  //I use a getter
  get products() {
    return this.cartService.getProducts()
    //you also can use
    return this.cartService.products;
  }
  constructor(private cartService: CartService) {}
  ngOnInit() {
    this.calculeTotal();
  }

  add() {

    //well I add a "fool product"
    const date = new Date();
    this.cartService.addToCart({
      Name: 'fool ' + date.getSeconds(),
      PriceWithIVA: 100,
    });
    this.calculeTotal();
  }

  clear() {
    this.cartService.clearCart();
    this.calculeTotal();
  }

  //After any operation we should call to CalculateTotal

  private calculeTotal() {
    this.totalPrice = this.products.reduce(
      (acc, product) => acc + product.price,
      0
    );
  }
}

您的服务

@Injectable({
  providedIn: 'root',
})
export class CartService {
  products: any[] = [];
  cartQuantity = 0;
  constructor() {
    //get the "localstorage"
    const local = localStorage.getItem('products');

    //if exist, use JSON.parse, else return an empty array
    const products = local ? JSON.parse(local) : [];

   //map to be sure the "price" is a number
    this.products = products.map((x: any) => ({
      ...x,
      price: +(x.price || 0),
    }));

   //really it's unnecesary
    this.cartQuantity = products ? products.length : 0;
  }
  addToCart(product: any) {
    this.products.push({
      name: product.Name,
      image: product.Attachment,
      price: +product.PriceWithIVA,
    });
    
    //but we need actualize the value of qauntity
    this.cartQuantity = products ? products.length : 0;

    localStorage.setItem('products', JSON.stringify(this.products));
  }

  getProducts() {
    return this.products;
  }

  clearCart() {
    localStorage.removeItem('products');
    this.products = [];
    this.cartQuantity = 0;
  }
}

A simple stackblitz

ttcibm8c

ttcibm8c2#

尝试使用此方法,这是添加到本地存储的更清晰的代码。

addToCart(product: ProductDTO) {

  let products;

  if (localStorage.getItem ('products')) {
      products = JSON.parse(localStorage.getItem('products'));
  } else {
      products = [];
  }

  products.push ({
      name: product.Name,
      image: product.Attachment,
      price: product.PriceWithIVA
  })

  localStorage.setItem ('products', JSON.stringify(products));
  this.products = products;
}

还要将以下内容添加到保存this.products的组件中,以便在每次加载组件时使用本地存储。

ngOnInit(): void {
    this.products = JSON.parse(localStorage.getItem('products'));
  }

相关问题