情景:
问题:
解决方案:
过程: 为了在网站重新加载后获取项目,我订阅了一个服务,该服务从持久性存储中收集所有项目。 当用户进入购物车时(通过重新加载或通过应用程序内的直接导航)设置项目的代码几乎相同,因为订阅仅在网站重新加载后触发。
示例代码:
ngOnInit() {
// We need the double code here because:
// 1. The normal code is for normal navigation of the user (e.g. from the home component to the shopping cart).
// The shopping cart is already filled with items
this.shoppingCart = this.shoppingcartService.shoppingCart;
// 2. The user reloads the site (or returns later after having it closed) and the shopping cart is filled (in the background)
// from the persistance store and emitted to all listeners of the application.
this.shoppingcartEmitter = this.shoppingcartService.shoppingCartEmitter.subscribe( shoppingcart => {
this.shoppingCart = shoppingcart;
});
}
这是一个简化版本,但我可以看到我需要两行同样的行为。
问题:是否有可能避免双重代码? 我的问题是我需要处理购物车中的物品,我必须编写代码,以便在订阅内部和外部使用购物车。
答案 0 :(得分:0)
你能做的就是把这两件事合并在一起
this.shoppingcartEmitter = this.shoppingcartService.shoppingCartEmitter.subscribe( shoppingcart => {
this.shoppingCart = shoppingcart.concat(this.shoppingcartService.shoppingCart);
}