首页 > 解决方案 > 使用 Subject/Observable 更新购物车中商品的显示

问题描述

我正在创建一个应用程序,用户在其中将商品添加到他们的购物车中,然后它会在本地存储中跟踪这些商品。当用户单击一个组件中的添加按钮时,我需要导航栏实时更新项目数量,但我无法使用事件发射器来设置我的应用程序。

我正在寻找的功能很简单,当我添加一个项目并将其放入本地存储时,我的导航栏中购物车徽标旁边的数字应该增加 1。我知道这可以使用 Observables 和 Subjects 来处理,我我只是很难理解它。我已经将代码从组件移动到服务开始,因为我认为这将允许两个组件与其通信。我可以使用该服务将项目正确添加到本地存储,但在那之后我被困在我需要跟踪服务添加的项目数量的地方。

这是服务:

@Injectable({
  providedIn: 'root'
})
export class MenuService {
  public apiRoot: string = `http://localhost:3000`;
  orders;

  constructor(private http: HttpClient) { }

  order(id, name, options, price) {
    //confirm the order is correct
    const orderConfirmed = confirm("Add this item to your cart?");

    if (orderConfirmed) {
    let order = new Order(id, name, options, price)   

    //get and set any existing orders from local storage or set to a blank array if there are none
    this.orders = localStorage.getItem('order') ? JSON.parse(localStorage.getItem('order')) : [];

    //push to our orders array
    this.orders.push(order)

    //store in localStorage
    localStorage.setItem('order', JSON.stringify(this.orders)) 
    }
  }

然后这是我的 navbar.ts:

export class NavbarComponent implements OnInit {
  itemsInCart;
  constructor() { }

  getItemsInCart() {
    this.itemsInCart = JSON.parse(localStorage.getItem('order'))
  }

  ngOnInit() {
    this.getItemsInCart();
  }

}

现在我只是直接从本地存储中提取项目并显示它们,但显然如果我要添加其他项目,这将无法实时工作,基本上我想制作位于路由器插座上方的导航栏组件能够订阅 中的this.orders属性,以便在用户将商品添加到购物车时实时MenuService跟踪 的长度。this.orders对不起,如果这看起来很明显,还在学习!

标签: angularobservablesubject

解决方案


Add a Subject to your service, call it in your order method and subscribe to it in yur component

storage.service.ts

orders
ordersChanged = new Subject<any>()

order(){
   //your code
   this.ordersChanged.next(this.orders)
    }

component.ts

itemsInCart

constructor(private storageService: StorageService){}

ngOnInit(){
   this.storageService.ordersChanged.subscribe(items => itemsInCart = items)
}

推荐阅读