在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:'
