在localStorage中更改特定键时通知其他组件 - Angular

时间:2017-11-19 10:30:35

标签: angular rxjs subject-observer

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

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

解决方案可用here但是会​​监视localStorage中的所有密钥。

感谢您的帮助。 感谢。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

使用主题。

每当您更新产品密钥时,请在主题上调用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
  }
);