【问题标题】:Javascript localStorage not available in another component unless I refresh the page除非我刷新页面,否则 Javascript localStorage 在其他组件中不可用
【发布时间】:2019-12-22 00:49:21
【问题描述】:

编辑:这不是 how to retrieve the value from localstorage 的副本。我的情况完全不同,事实上,这不是本地存储的问题,而是 Angular 的工作方式。

我正在开发一个 Angular7 应用程序。

我有一个将令牌设置为 localStorage 的组件:window.localStorage.setItem("oauth_token", oauth_token) 然后重定向到首页:this.router.navigate(['/'])

根组件现在应该可以从 localStorage window.localStorage.getItem("oauth_token") 读取,但除非我手动刷新页面,否则该值为 null。

当我检查 Chrome 开发工具时,我可以在本地存储中看到令牌,那么为什么我需要刷新页面? 我能做些什么来克服这个问题?

【问题讨论】:

  • @weegee 不,它看起来不一样。我希望该值在不刷新页面的情况下可用。
  • 您是否调查过使用计时器来执行管理功能并可能为您更新页面?
  • @SPlatten 我在重定向到主页之前尝试过使用 setTimeout,但是没有用
  • 你能分享一些你的代码吗?
  • @Sergio,请改用 setInterval,setTimeout 为您提供一次性计时器。

标签: javascript angular typescript local-storage angular7


【解决方案1】:

这与本地存储无关。您的根组件需要触发或刷新才能访问本地存储或数据中的任何更改。

当您重定向到主页时,只会执行来自主页组件的代码,而不是来自父组件或根组件的代码。

您需要在服务文件中声明一个变量。因此,每当您更新本地存储时,您都必须更新服务文件变量的值。您可以在根组件中访问此变量。因此,如果服务变量有任何变化,就会触发触发器,您可以更新本地存储。检查链接以获取示例代码https://github.com/resistcheat/angular-variable-as-observable

创建服务文件

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CommonService {
  data: any;
  private items: BehaviorSubject<any> = new BehaviorSubject<any>(this.data);
  items$: Observable<any> = this.items.asObservable();
  constructor(private http: HttpClient) { }
  setLocalStorageData() {// Call this function to set localstorage
    localStorage.setItem("oauth_token", oauth_token)
    this.data = oauth_token;
  }
}

//当this.data改变时触发。将以下代码添加到您的根组件中

constructor(private commonService: CommonService) { }
items: any;
subscription: Subscription; //import { Subscription } from 'rxjs';

ngOnInit() {
  this.subscription = this.commonService.items$.subscribe(items =>  {
    this.items = JSON.stringify(items));
    console.log(localStorage.getItem("oauth_token"));
  }
}

ngOnDestroy() {
  this.subscription && this.subscription.unsubscribe();
}

【讨论】:

    【解决方案2】:

    试试没有窗口,像这样:

    localStorage.getItem("oauth_token")...
    

    【讨论】:

    • 当你在控制台上写 localStorage 你会得到什么?
    猜你喜欢
    • 1970-01-01
    • 2012-11-12
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 2013-06-28
    • 1970-01-01
    相关资源
    最近更新 更多