【问题标题】:Notify other components when a particular key is changed in localStorage - Angular在 localStorage 中更改特定键时通知其他组件 - Angular
【发布时间】:2017-11-19 20:39:09
【问题描述】:

我的问题很笼统。我想观察 localStorage 的角度变化,但 localStorage 中的每个键都需要单独观察。

例如,我在 localStorage 中有一些产品列表,位于某个键 _products_ 比方说,它存储了一系列产品。现在,每当我添加新产品并将其附加到 localStorage 中的 _products_ 键时,我希望其他组件知道 _products_ 已修改。

here 提供了一个解决方案,但它会监视 localStorage 中的所有密钥。

感谢您的帮助。 谢谢。

【问题讨论】:

  • 调整它,并发出包含已修改键的事件。然后观察者只需要过滤他们感兴趣的事件。
  • @JBNizet 你能提供一些示例代码吗?我不知道该怎么做。

标签: angular rxjs subject-observer


【解决方案1】:

您应该在共享服务中定义 localStorage,该服务可供所有组件访问,并使用 Subject 来跟踪 localStorage 内部的更改。Hereby an example to use Subject

【讨论】:

    【解决方案2】:

    使用主题。

    每当您更新产品密钥时,请在主题上调用 next()。

    现在在任何其他文件中,如果您想观看对此密钥所做的更改,只需订阅此主题即可;

    这是更新密钥的服务文件中的代码:

    @Injectable()
    class KeyService {
      let storageObservable = new Subject<Product>();//use anything you want instead of the Product
    
      .
      .
      .
    
      methodWhereYouUdateTheProductKey(){
        //do your things
        //
        //
        this.storageObservable.next(newValueOfKey);
      }
    
      public followProducstKey(): Oservable<Product> {
        return this.storageObservable;
      }
      
    }

    这是观察该键变化的代码:

    this.keyService.followProducstKey.subscribe(
      data => {
        console.dir(data);
        //do anything you want with the data you passed on the next() function
      }
    );

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-27
      • 2012-12-02
      • 2023-03-19
      • 2023-01-12
      • 1970-01-01
      • 2016-01-19
      • 1970-01-01
      • 2018-10-17
      相关资源
      最近更新 更多