本地存储使用 Angular

huangapple go评论63阅读模式
英文:

Local Storage using Angular

问题

以下是您的代码的中文翻译:

我正在开发一个电子商务网站,尝试设置本地存储以保存购物车中的物品。

当我将产品添加到购物车时一切都正常,但一旦刷新购物车页面,所有产品都会消失。

我尝试设置本地存储,但无法找出哪里出错了...

我的浏览器对本地存储权限没有问题(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;
}

希望这能帮助您解决问题。

英文:

I'm developing an e-commerce and I'm trying to set local storage to hold the elements inside the cart.

All fine when i add a product to the cart and all but once i refresh the cart page, all products just disappear.

I tried set the local storage and i can't figure where i'm wrong...

My browser is fine with local storage permissions (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;
}

答案1

得分: 1

以下是翻译好的部分:

尝试使用以下代码替代这是更清晰的代码用于将产品添加到本地存储

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'));
}
英文:

Try with this instead which is way more clear code to add to your local storage.

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

Also add the following to your component that holds the this.products to use the local storage each time the component loads.

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

答案2

得分: 1

在你的服务构造函数中,你应该询问关于 "localStorage.getItem ('products')"。

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

更新
@Jany,你需要注意变量的名称 - 你将数据存储为名称、价格和图像,但当你添加到购物车时,接收到一个对象,其中包含Name、Attachment和PriceWithIVA。

此外,在你的服务和购物车中都有一个名为products的变量,也许使用一个getter更好。

我fork了你的代码。

export class CartComponent implements OnInit {
  totalPrice: number;

  //我使用一个getter
  get products() {
    return this.cartService.getProducts();
    //你也可以使用
    return this.cartService.products;
  }
  constructor(private cartService: CartService) {}
  ngOnInit() {
    this.calculeTotal();
  }

  add() {
    //好吧,我添加了一个 "愚蠢的产品"
    const date = new Date();
    this.cartService.addToCart({
      Name: '愚蠢的 ' + date.getSeconds(),
      PriceWithIVA: 100,
    });
    this.calculeTotal();
  }

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

  //在任何操作之后,我们应该调用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() {
    //获取 "localstorage"
    const local = localStorage.getItem('products');
    
    //如果存在,使用JSON.parse,否则返回一个空数组
    const products = local ? JSON.parse(local) : [];

    //映射以确保 "price" 是一个数字
    this.products = products.map((x: any) => ({
      ...x,
      price: +(x.price || 0),
    }));

    //实际上这是不必要的
    this.cartQuantity = products ? products.length : 0;
  }
  addToCart(product: any) {
    this.products.push({
      name: product.Name,
      image: product.Attachment,
      price: +product.PriceWithIVA,
    });
    
    //但是我们需要更新qauntity的值
    this.cartQuantity = this.products ? this.products.length : 0;

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

  getProducts() {
    return this.products;
  }

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

一个简单的StackBlitz链接

英文:

In constructor of your service you should ask about "localStorage.getItem ('products')"

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

Update*
@Jany, you need pay attention to the name of the variables -you store the data as name, price and image but when you add to cart received an object with but received Name, Attachment and PriceWithIVA.

Futhermore you has variable products in service and in your card, perhafs it's good use a getter.

I forked your code

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

Your service

@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

huangapple
  • 本文由 发表于 2023年4月11日 16:33:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75983893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定