【问题标题】:implement webstorage with observable in angular application在角度应用程序中实现可观察的网络存储
【发布时间】:2018-11-27 09:02:14
【问题描述】:

我在我的 Angular 应用程序中使用 ngx-webstorage 库。 问题是当我调用intitalizeIntro()时,主要组件已经初始化了

我想监听本地存储的变化并在主组件中执行 introDashboard.start() 方法。

这是我尝试过的。

child.component.ts

initializeIntro(value: string){
this.localStorage.store('selectedIntro', value); // value ='Dashboard'
console.log('Intro Activated ' + value); 
}

main.component.ts

ngOnChanges(){
this.localStorage.observe('selectedIntro') // i can see value stored in local storage
 .subscribe((newValue) =>{
   if(newValue === 'Dashboard'){ // but not able to enter if loop
     console.log('inside introDashboard loop');
     introDashboard.start();
   }
 });
}

我应该使用其他生命周期钩子还是如何检测本地存储的变化。如果有人可以提供解释或指出我要检查的材料,我会很高兴。

我觉得我应该在某处使用 emit() ,但无法理解如何使用。

【问题讨论】:

    标签: angular local-storage observable


    【解决方案1】:

    您可以尝试添加 ngOnInit 方法而不是 ngOnchanges。

    @LocalStorage('selectedIntro') boundAttribute;
    
    ngOnInit(){
       this.localStorage.observe('selectedIntro') // i can see value stored in local storage
        .subscribe((newValue) =>{
        if(newValue === 'Dashboard'){ // but not able to enter if loop
         console.log('inside introDashboard loop');
         introDashboard.start();
        }
      });
    }
    

    【讨论】:

    • 它工作了,但是如何多次调用 oninit() 方法,或者在 onInit() 中调用的 subscribe 方法现在监听 localStorage 变量的变化?
    • Rxjs 中的订阅方法是一个数据流,它会发出数据流并通知订阅者。投票对他人很有帮助。
    猜你喜欢
    • 2021-10-19
    • 1970-01-01
    • 2017-05-23
    • 2017-08-02
    • 2016-09-25
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多