组件交互角度

时间:2017-12-08 11:31:30

标签: angular

需要一些帮助。我在类似页面上有产品目录和购物车,我想在按下“购买”按钮时在购物车中显示项目。当按下按钮时,该项目将转到localStorage,并且仅在F5之后才会显示在购物车中。我想我应该使用Input decorater,但是如何实现呢?也许正确的方法是使用服务和观察,但我现在做角度弱。还需要从购物车中删除商品,我应该为此重写本地存储,对吗?

目录

  <div class="content">
<div class="item" *ngFor="let auto of auto; let i=index">
    <div> <img src="../../assets/db/{{auto.photo}}" alt=""></div>
  <div class="text">
    <p>{{auto.name}} - {{auto.price}} руб.</p>
    <p><input type="submit" value="Купить" (click)="toCart(i)"></p></div> 
</div>

  auto: any;
cart=[];
price=[];

constructor(private service:DataService) { }

ngOnInit() {
  this.getItems();
}
getItems(){
  this.service
     .getItems()
     .subscribe(goods => {
       this.auto = goods;
     } )
}

toCart(i){
  this.cart.push(this.auto[i]);
  this.price.push(this.auto[i].price);
  localStorage.setItem("cart",JSON.stringify(this.cart));
  localStorage.setItem("price",JSON.stringify(this.price));

}

购物车组件

export class CartComponent implements OnInit {
list = localStorage.getItem("cart");
names = JSON.parse(this.list);
len = this.names.length;
price = this.names.price;
Message: string;   


constructor() { }

 ngOnInit() { 
 }

send(){
  this.Message = "Готово";
  localStorage.setItem('cart',JSON.stringify(""));
 }  

// remove(i){
//     let newlist = this.names.slice(this.names[i],1);
//     console.log(newlist);
//     this.len = this.names.length - 1;
//  }

}

购物车模板

<div class="content">
<li *ngFor="let name of names; let i=index">
  <p>{{name.name}} - {{name.price}}руб.</p>
<button (click)="remove(i)">Удалить</button> 
  <!-- <button (click)= "add(i)">Добавить </button>   -->
</li>
<p>Количество: {{len}}  </p>
{{Message}}
<p><input type="submit" value="Оформить заказ" (click)="send()"></p>

1 个答案:

答案 0 :(得分:0)

请尝试将list = localStorage.getItem("cart"); names = JSON.parse(this.list);移至ngOnInit()中的cart.component

这可确保每次加载购物车页面时,都会从本地存储更新该值。