javascript - 除非我刷新页面,否则 Javascript localStorage 在其他组件中不可用
问题描述
编辑:这不是如何从 localstorage 检索值的重复。我的情况完全不同,事实上,这不是本地存储的问题,而是 Angular 的工作方式。
我正在开发一个 Angular7 应用程序。
我有一个组件将令牌设置为 localStorage:window.localStorage.setItem("oauth_token", oauth_token)
然后重定向到主页:this.router.navigate(['/'])
根组件现在应该能够从 localStorage 读取window.localStorage.getItem("oauth_token")
,但是除非我手动刷新页面,否则该值为 null。
当我检查 Chrome 开发工具时,我可以在本地存储中看到令牌,那么为什么我需要刷新页面?我能做些什么来克服这个问题?
解决方案
它与本地存储无关。您的根组件需要触发或刷新才能访问本地存储或数据中的任何更改。
当您重定向到主页时,只会执行来自主页组件的代码,而不是来自父组件或根组件的代码。
您需要在服务文件中声明一个变量。因此,每当您更新本地存储时,您都必须更新服务文件变量的值。您可以在根组件中访问此变量。因此,如果服务变量有任何变化,就会触发触发器,您可以更新本地存储。检查链接以获取示例代码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();
}
推荐阅读
- python - 无法理解 Tkinter 配置
- scala - scalatest 断言任何一个都是正确的导致符号文字被弃用警告
- android - RadioGroup 到 if 语句?
- sql-query-store - 了解 SQL 查询
- php - Laravel 8 动态模型工厂?
- java - Spring Boot 从 1.5.2 迁移到 2.0.3 和 Java 8 到 11
- java - 循环遍历二维数组。性能问题
- gradle - 如何下载 org.gradle.kotlin.dsl 的源 jar 文件
- mysql - 分片与分区数据库
- arrays - 如何在 Google Apps Script Web 应用程序中提取 JSON 对象?