JavaScript的localStorage在另一个组件中不可用,除非我刷新页面。

3

编辑:这不是如何从本地存储中检索值的重复问题。我的情况完全不同,事实上,这不是与本地存储有关,而是与Angular的工作方式有关。

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

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

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

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


你考虑过使用定时器执行后勤功能,或者为您更新页面吗? - SPlatten
@SPlatten 我之前尝试过在重定向到主页之前使用setTimeout,但是它没有起作用。 - Sergio
@SPlatten setInterval会一遍又一遍地循环执行你的代码,不要这样做,否则会破坏你的程序。 - Alfian Busyro
@SPlatten 不,setInterval 绝对没用,除非你用它来做动画。我假设你对 JS 有很好的理解。 - Alfian Busyro
@arufian,再次取决于您如何使用它以及您对其进行的操作,就像任何功能一样,如果实现不良,它可能表现不佳。 - SPlatten
显示剩余11条评论
2个回答

3

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

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

您需要在服务文件中声明一个变量。因此,每当您更新本地存储时,您都将更新服务文件变量的值。您可以在根组件中访问此变量。因此,如果服务变量有任何更改,将会触发一个触发器,并且您可以更新本地存储。查看链接以获取示例代码: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发生变化时,触发Trigger。将以下代码添加到您的根组件中。
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();
}

1

try without window, like that:

localStorage.getItem("oauth_token")...

当你在控制台上写 localStorage 时,你会得到什么? - tehila

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接