【问题标题】:Angular - How to always get the newest data at localStorage?Angular - 如何始终在 localStorage 获取最新数据?
【发布时间】:2020-01-03 01:38:20
【问题描述】:

我知道有很多关于SO谈论这个问题的问题,但是直到现在我还没有找到任何可以解决这个问题的话题。基本上,我有一个服务负责从服务中获取数据并在本地保存,还有一个组件来显示这些数据。但是每次我发送新请求时,组件都会显示旧数据而不是新数据。我已经尝试过:

localStorage.removeItem(this.dataToShow);
localStorage.setItem(this.dataToShow, JSON.stringify(content));

但即使这样也解决了这个问题。

【问题讨论】:

    标签: angular web-services local-storage


    【解决方案1】:

    您需要在本地存储值更新时更新组件数据。是吗?

    在 Angular 中,没有绑定到本地存储。换句话说,每次更新时,您都必须从本地存储中获取项目值。

    因此我建议您导入服务并订阅主题,以便将任何更改传播到组件。

    所以在您的服务中调用 Subject.next() 将消息发送到 observable。 所以订阅者会收到通知。

    这是一个帮助完整链接。 http://jasonwatmore.com/post/2016/12/01/angular-2-communicating-between-components-with-observable-subject

    【讨论】:

    • 我正在使用 subscribe 方法总线仍然遇到同样的问题。
    • 你用过主题吗? subject.next() 怎么样?请参考链接。
    【解决方案2】:

    好吧,据我所知,您想首先显示本地存储的数据,您需要像这样在本地保存数据 localStorage.setItem('mean-token', token); mean-token 是名称,token 是对象,您可以通过名称调用对象: const name = localStorage.getItem('mean-token');要删除它,您可以使用: localStorage.removeItem('mean-token') 希望那行,如果不是你能更好地解释这个问题

    【讨论】:

      【解决方案3】:

      我正在使用ngx-webstorage-service

      您需要初始化一个 Observable 方法,该方法返回一个 Subject 变量来跟踪本地存储服务中的变化。

      import { Observable, Subject } from 'rxjs';
      import { LOCAL_STORAGE, StorageService } from 'ngx-webstorage-service';
      import { Inject, Injectable } from '@angular/core';
      
      // Key used to access status in local storage
      const STATUS_STORAGE_KEY = 'status_test';
      
      @Injectable()
      export class LocalStorageService {
        private storageStatus = new Subject<string>();
        constructor (
          @Inject(LOCAL_STORAGE)
          private storage: StorageService)
        {}
      
        watchStorage(): Observable<any> {
          return this.storageStatus.asObservable();
        }
      
        // Set Method
        public setStatus(status: boolean) {
          this.storage.set(STATUS_STORAGE_KEY, status);
          this.storageStatus.next('changed'); // tell subscribers storage status is updated
        }
      
        // Get Method
        public getStatus() {
          return this.storage.get(STATUS_STORAGE_KEY);
        }
      }
      

      在您的 component.ts 中

      将新数据设置到本地存储将触发 Behavior 变量,然后将通知订阅者进行了更改

      this.localStorage.setStatus(true);
      

      订阅 observable,这样每当存储添加新数据时,它也会更新。

      this.localStorage.watchStorage().subscribe(() => {
        this.updatedStatus = this.localStorage.getStatus();
      })
      

      【讨论】:

        猜你喜欢
        • 2022-06-11
        • 1970-01-01
        • 1970-01-01
        • 2017-07-29
        • 2021-07-10
        • 2019-04-16
        • 2020-11-13
        • 2014-04-06
        • 2019-11-17
        相关资源
        最近更新 更多