当前位置: 首页 > Web前端 > HTML

Angularserver-renderedapplications的错误提示-localStorageisnotdefined

时间:2023-03-29 11:25:12 HTML

在Angular应用程序开发中,我们在TypeScript代码中调用localStorage。它通过键从本地存储中检索数据。但是在服务器上,此代码崩溃并显示错误消息:ReferenceError:localStorageisundefined在服务器上运行Angular应用程序时,全局空间中缺少标准浏览器API。例如,在服务器端渲染模式下,开发人员不能像在客户端渲染环境中那样使用直接访问全局文档对象。要获取对文档的引用,您必须使用DOCUMENT标记和Angular的依赖注入机制DI。不要通过全局空间使用浏览器API,而是使用DI替换或禁用浏览器实现,以便在服务器上安全地使用这些API。参考代码如下:import{Component,Inject,NgModule}from'@angular/core';从“@ng-web-apis/common”导入{LOCAL_STORAGE};@Component({...})exportclassSomeComponent{constructor(@Inject(LOCAL_STORAGE)localStorage:Storage){localStorage.getItem('key');}}上面的示例使用了@ng-web-apis/common包中的LOCAL_STORAGE令牌。但是当我们在服务器上运行这段代码时,我们得到一个错误。只需从AppServerModule的提供程序中的@ng-web-apis/universal包中添加UNIVERSAL_LOCAL_STORAGE并传递令牌LOCAL_STORAGE以获取服务器的localStorage实现。从'@angular/core'导入{NgModule};从'@angular/platform-server'导入{ServerModule};从'./app.module'导入{AppModule};从'./app.import{AppComponent}。component';import{UNIVERSAL_LOCAL_STORAGE}from'@ng-web-apis/universal';@NgModule({imports:[AppModule,ServerModule,],providers:[UNIVERSAL_LOCAL_STORAGE],bootstrap:[AppComponent],})exportclassAppServerModule{}看下面的条件渲染代码:<>@Component({selector:'ram-root',template:'',styleUrls:['./app.component.less'],})exportclassAppComponent{isServer=isPlatformServer(this.platformId);constructor(@Inject(PLATFORM_ID)privateplatformId:Object){}}此Angular组件需要获取PLATFORM_ID、目标平台,并了解类的公共属性。该属性将与模板中的ngIf指令一起使用。我们有一个更优雅的实现:首先创建一个注入令牌:然后创建自定义指令:@Directive({selector:'[ifIsServer]',})exportclassIfIsServerDirective{constructor(@Inject(IS_SERVER_PLATFORM)isServer:boolean,templateRef:TemplateRef,viewContainer:ViewContainerRef){if(isServer){viewContainer.createEmbeddedView(templateRef);然后直接在组件上使用这个结构指令:<>@Component({selector:'ram-root',template:'',styleUrls:['./app.component.less'],})exportclassAppComponent{}extraattributeshavebeenremovedfromthecomponent.Component模板现在更简单,只需关注它试图实现的业务逻辑。