【发布时间】:2019-05-02 21:06:03
【问题描述】:
我正在创建一个应用程序,用户可以在其中将商品添加到他们的购物车中,然后它会在本地存储中跟踪这些商品。当用户单击一个组件中的添加按钮时,我需要导航栏实时更新项目数量,但我无法使用事件发射器来设置我的应用程序。
我正在寻找的功能很简单,当我添加一个项目并将其放入本地存储时,我的导航栏中购物车徽标旁边的数字应该增加 1。我知道这可以使用 Observables 和科目,我只是很难理解它。我已经将代码从组件移动到服务开始,因为我认为这将允许两个组件与其通信。我可以使用该服务将项目正确地添加到本地存储中,但在那之后我陷入了困境,我需要跟踪服务中添加的项目数量。
这里是服务:
@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();
}
}
现在我只是直接从本地存储中提取项目并显示它们,但显然如果我要添加其他项目,这将无法实时工作,基本上我想制作我的导航栏组件,它位于router-outlet 能够订阅MenuService 中的this.orders 属性,以便在用户将商品添加到购物车时实时跟踪this.orders 的长度。抱歉,如果这看起来很明显,仍在学习中!
【问题讨论】:
标签: angular observable subject