【问题标题】:Is double code avoidable when working with .subscribe() in Angular 2?在 Angular 2 中使用 .subscribe() 时是否可以避免双重代码?
【发布时间】:2017-04-20 11:06:17
【问题描述】:

场景:

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

问题:

  • 如果用户重新加载购物车,所有商品都会消失

解决方案:

  • 所有项目都通过持久性存储进行存储,并且只有在用户重新加载站点时才会被调用

流程:

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

示例代码:

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

这是一个简化版本,但可以看出我需要两行代码来实现相同的行为。

问题:

有没有办法避免双码?

我的问题是我需要处理购物车中的商品,而且我必须编写代码来处理订阅内外的购物车。

【问题讨论】:

  • 为什么不更改服务,将购物车中的选定商品保存到local storage or session storage?当服务初始化时,它会检查存储并加载项目(如果有的话)。这样在页面刷新的情况下,项目不会丢失。
  • 是的,会话存储(在这种情况下)可以解决我的问题。但我想知道是否可以在此处添加其他解决方案或最佳实践 - 以防会话存储没有帮助。
  • 我总是订阅发射器。如果不需要去商店,您可以使用Observable.of 在服务中直接返回一个新的可观察对象。

标签: javascript angular angular2-services


【解决方案1】:

你可以做的就是把这两件事合并在一起

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-11
    • 2013-09-17
    • 2012-08-12
    • 2013-10-23
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    相关资源
    最近更新 更多