NestJs Angular Universal ReferenceError:未定义 sessionStorage [英] NestJs Angular Universal ReferenceError: sessionStorage is not defined
问题描述
请帮忙,我有一个使用 angular 通用(angular 8 和 NestJs)的应用程序.我正在尝试访问角度组件(onInit
)内的会话存储,但 NestJs 给了我以下信息:ERROR ReferenceError: sessionStorage is not defined
.在查看 angular DI 然后我尝试了以下操作:
Please assist, i have an application using angular universal (angular 8 and NestJs). i am trying to access session storage inside an angular component(onInit
) but NestJs is giving me the following : ERROR ReferenceError: sessionStorage is not defined
. After looking at angular DI I then tried the following :
export const BROWSER_STORAGE = new InjectionToken<Storage>('Browser Storage', {
providedIn: 'root',
factory: () => window.sessionStorage
});
然后在我的组件中:
constructor(@Inject(BROWSER_STORAGE) public storage: Storage) {}
ngOnInit(): void {
this.storage.setItem('store', 'store');
}
现在收到以下错误ERROR TypeError: this.storage.setItem is not a function
.如何使用 angular Universal(angular 8 和 NestJs)设置/获取会话存储数据.
Now getting the following error ERROR TypeError: this.storage.setItem is not a function
. How can i set/get session storage data using angular universal (angular 8 and NestJs).
推荐答案
感谢 David.为了让 NestJs 不执行 this.storage.setItem('store', 'store');
必须注入 PLATFORM_ID
并使用 isPlatformBrowser
作为如下:
Thanks to David. To make NestJs not to execute this.storage.setItem('store', 'store');
had to inject PLATFORM_ID
and use isPlatformBrowser
as follows :
constructor(
@Inject(BROWSER_STORAGE) public storage: Storage,
@Inject(PLATFORM_ID) public platformId: object
) {}
然后在 ngInit 中:
Then inside ngInit:
ngOnInit(): void {
if (isPlatformBrowser(this.platformId)) {
sessionStorage.setItem('store', 'store');
this.storage.setItem('storeDI', 'storeDI');
}
}
isPlatformBrowser(this.platformId)
将在服务器端返回 false
,在浏览器端返回 true
.
isPlatformBrowser(this.platformId)
will return false
on the server side and true
on the browser side.
这篇关于NestJs Angular Universal ReferenceError:未定义 sessionStorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!