2017-04-20 72 views
0

场景:Angular 2:使用.subscribe()时可避免双重代码?

  • 用户是一个页面上,选择他想要在他的购物车项目
  • 项目是一旦用户输入他看到所有的购物车放入(全球)服务
  • 他项目(其被加载到经由服务组件)

问题:

  • 如果用户重新加载购物车,所有物品都不见了

解决方案:

  • 所有项目均通过持久性存储保存,将被称为只有当用户重新载入网站

过程: 为了获取站点重新加载后的项目,我正在订阅一个服务,该服务从持久性存储中收集所有项目。 当用户进入购物车时(通过重新加载或通过应用程序内的直接导航),用于设置项目的代码几乎相同,因为只有在网站重新加载后才会触发订阅。

示例代码:

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; 
    }); 
} 

这是一个简化版本,但我们可以看到,我需要两行相同的行为。

问题:有没有可能避免双重代码? 我的问题是,我需要使用shoppingcart中的项目,并且我将不得不编写代码来处理订阅内部和外部的shoppingcart。

+1

,使其坚持在车中的选择项目[本地存储或会话存储(HTTPS为什么不改变服务:// WWW .w3schools.com/HTML/html5_webstorage.asp)?当服务初始化时,它会检查存储并加载项目(如果有的话)。然后,在页面刷新的情况下,这些项目不会丢失。 – Igor

+0

是会话存储(在这种情况下)将解决我的问题。但是我想知道是否还有其他解决方案或最佳实践可以在这里添加 - 如果会话存储不起作用。 – Saerdn

+0

我只是总是订阅发射器。如果不需要访问商店,则可以返回一个新的observable,该observable使用'Observable.of'直接在服务中返回结果。 – Igor

回答

0

你可以做的就是这两样东西融合在一起

this.shoppingcartEmitter = this.shoppingcartService.shoppingCartEmitter.subscribe(shoppingcart => { 
     this.shoppingCart = shoppingcart.concat(this.shoppingcartService.shoppingCart); 
}