angular - 使用 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
对不起,如果这看起来很明显,还在学习!
解决方案
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)
}
推荐阅读
- c# - 扩展对象数组列表是否会生成一个新对象?
- javascript - 我想在 HTML 元素中显示函数的返回值,但返回值是 NAN
- c++ - 放置运算符新查找
- xamarin - Xamarin Forms 自定义控件绑定问题
- swift - 可选键的默认枚举值
- python - “用户警告:Matplotlib 当前使用的是 agg,这是一个非 GUI 后端,因此无法显示该图。” 在 Pycharm 上用 pyplot 绘制图形时
- r - 如何将反斜杠替换为 R 中整个 CSV 文件的正斜杠?
- json - React 认为我的“AbstractContract”是一个“对象”并且在我调用方法时不会呈现
- python - 为每个 Pandas 单元格设置相同的字典
- javascript - 在 Javascript 中从非关系数据库构建 JSON 树时遇到问题