我在我的角度项目中收到错误“ReferenceError:localStorage 未定义”

问题描述 投票:0回答:1

在我的 Angular 项目中,我想使用 localStorage。 但我收到错误。

这是我的代码。

const siteId = this.route.snapshot.queryParamMap.get('SiteId');
if (siteId) {
  this.globalService.setLocalStorage('site_id',siteId);
} else if (!localStorage.getItem("site_id")) {
  this.snackbarService.openSnackbar("Site id is missing", 'error');
}

这是错误。


ERROR ReferenceError: localStorage is not defined
    at inject (F:\companies\IOT-Billing\source\OnLineSignUp\src\app\modules\auth\login\login.component.ts:16:5)
    at callHookInternal (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:5640:10)
    at callHook (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:5655:7)
    at callHooks (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:5629:9)
    at executeInitAndCheckHooks (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:5598:5)
    at refreshView (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10505:11)
    at detectChangesInView (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10657:5)
    at detectChangesInViewIfAttached (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10640:3)
    at detectChangesInEmbeddedViews (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10616:7)
    at refreshView (F:\companies\IOT-Billing\source\OnLineSignUp\.angular\cache\18.2.3\vite\deps_ssr\chunk-DH64UGMO.js:10517:5)

我想在 localStorage 中存储和获取令牌。

angular
1个回答
0
投票

当您将 Angular 应用程序与 SSR 一起使用时。服务器没有可用的

window
document
localStorage
对象,我猜测这是错误的原因。

只需将 localStorage 方法包装在 if 条件中,在执行操作之前检查它是否不是

undefined

if(typeof localStorage !== 'undefined') {
    localStorage.setItem("bgcolor", "red");
}
© www.soinside.com 2019 - 2024. All rights reserved.