Javascript 角度2:使用.subscribe()时可以避免双重代码?

Javascript 角度2:使用.subscribe()时可以避免双重代码?,javascript,angular,angular2-services,Javascript,Angular,Angular2 Services,情景: 用户在一个页面上,在他的购物车中选择他想要的项目 项目被放入(全局)服务 一旦用户进入shoppingcart,他就会看到他的所有项目(通过服务加载到组件中) 问题: 如果用户重新加载shoppingcart,则所有项目都将消失 解决方案: 所有项目都通过持久性存储存储,只有在用户重新加载站点时才会调用 过程: 为了在站点重新加载后获取项目,我订阅了一个从持久性存储中收集所有项目的服务。 当用户进入购物车时(通过重新加载或通过应用程序内的直接导航),设置项目的代码几乎相同,因

情景:

  • 用户在一个页面上,在他的购物车中选择他想要的项目
  • 项目被放入(全局)服务
  • 一旦用户进入shoppingcart,他就会看到他的所有项目(通过服务加载到组件中)
问题:

  • 如果用户重新加载shoppingcart,则所有项目都将消失
解决方案:

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

示例代码:

    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。

您可以做的是将这两件事合并在一起

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

为什么不更改服务,使其将购物车中的所选项目持久化?当服务初始化时,它将检查存储并加载项目(如果有)。然后,在页面刷新的情况下,这些项目不会丢失。是的,会话存储将(在这种情况下)解决我的问题。但我想知道是否还有其他解决方案或最佳实践可以添加到这里-以防会话存储没有帮助。我只会一直订阅发射器。如果不需要去商店,您可以使用
observable.of
返回一个新的observable,直接在服务中返回结果。