typescript调用localstorage
在 angular 应用开发中,我们在 typescript 代码里调用 localstorage.
它通过 key 从 local storage 中检索数据。 但是在服务器上,此代码崩溃并显示错误消息:
referenceerror: localstorage is undefined
在服务器上运行 angular 应用程序时,全局空间中缺少标准浏览器 api.
例如,在服务器端渲染模式下,开发人员不能像在客户端渲染环境下那样,直接访问全局文档对象。 要获得对文档的引用,必须使用 document 令牌和 angular 依赖注入机制 di.
不要通过全局空间使用浏览器 api,而是通过 di 来替换或禁用浏览器实现,以便在服务器上安全使用这些 api.
参考下面的代码:
import {component, inject, ngmodule} from '@angular/core'; import {local_storage} from '@ng-web-apis/common'; @component({...}) export class somecomponent { constructor(@inject(local_storage) localstorage: storage) { localstorage.getitem('key'); } }
上面的示例使用来自 @ng-web-apis/common 包的 local_storage 令牌。
错误分析
但是当我们在服务器上运行这段代码时,我们会得到一个错误。
只需从 appservermodule 的 providers 中添加来自 @ng-web-apis/universal 包的 universal_local_storage,并通过令牌 local_storage,这样就能获得服务器的 localstorage 实现。
import { ngmodule } from '@angular/core'; import { servermodule, } from '@angular/platform-server'; import { appmodule } from './app.module'; import { appcomponent } from './app.component'; import { universal_local_storage } from '@ng-web-apis/universal'; @ngmodule({ imports: [ appmodule, servermodule, ], providers: [universal_local_storage], bootstrap: [appcomponent], }) export class appservermodule {}
看下面这段条件渲染代码:
<> @component({ selector: 'ram-root', template: '<some-сomp *ngif="isserver"></some-сomp>', styleurls: ['./app.component.less'], }) export class appcomponent { isserver = isplatformserver(this.platformid); constructor(@inject(platform_id) private platformid: object){} }
这个 angular component 需要获取 platform_id、目标平台,并了解类的公共属性。此属性将在模板中与 ngif 指令一起使用。
优雅实现
创建injection token
<> export const is_server_platform = new injectiontoken<boolean>('is server?', { factory() { return isplatformserver(inject(platform_id)); }, });
创建自定义指令
@directive({ selector: '[ifisserver]', }) export class ifisserverdirective { constructor( @inject(is_server_platform) isserver: boolean, templateref: templateref<any>, viewcontainer: viewcontainerref ) { if (isserver) { viewcontainer.createembeddedview(templateref); } } }
然后直接在 component 上使用这个 structure directive 就可以了:
<> @component({ selector: 'ram-root', template: '<some-сomp *ifisserver"></some-сomp>', styleurls: ['./app.component.less'], }) export class appcomponent {}
额外的属性已从组件中移除。component 模板现在更简单了,只用专注于它要实现的业务逻辑。
以上就是angular 服务器端渲染错误消息localstorage is not defined解决分析的详细内容,更多关于angular 服务器端渲染错误消息解决的资料请关注代码网其它相关文章!
发表评论