首页 > 解决方案 > 用于 SSR 浏览器/服务器/应用程序的 Angular 通用模块拆分

问题描述

我正面临 Angular Universal 投掷的问题:

ERROR ReferenceError: document is not defined

这是试图访问服务器端文档的 Fullcalendar 模块,该模块在服务器上不存在。我想做的是遵循来自https://github.com/angular/universal/blob/master/docs/gotchas.md的 Angular Git hub 的指南,说:

如果您有一个由第三方提供的开箱即用不兼容通用的组件,那么除了您的基本应用程序模块之外,您还可以为浏览器和服务器(您应该已经拥有的服务器模块)创建两个单独的模块。基本应用程序模块将包含所有与平台无关的代码,浏览器模块将包含所有浏览器特定/服务器不兼容的代码,反之亦然。为了避免编辑过多的模板代码,您可以创建一个无操作组件来插入库组件

我创建了浏览器模块:

 import { NgModule } from '@angular/core';
 import { AppComponent } from './app.component';
 import { AppModule } from './app.module';
 import { CalendarModule } from './calendar/calendar.module';

 @NgModule({

 imports: [
   AppModule,
   CalendarModule // <---- this module will include the code that must only run on the browser
 ],
 bootstrap: [AppComponent]

})
export class AppBrowserModule { }

现在我不知道我应该修改哪些其他文件才能制作:

标签: angularserver-side-rendering

解决方案


我把事情复杂化了。为了避免在服务器端使用浏览器 api,我简单地将 FullCalendar 组件包装在 ng-template 中,如下所示:

在构造函数集 isBrowser 到 isPlatformBrowser

 constructor(
   @Inject(PLATFORM_ID) private platformId,
   private eventService: EventsService, 
   private router: Router){
     this.isBrowser = isPlatformBrowser(this.platformId);
     console.log(this.isBrowser)
  }

并在模板中:

<ng-container *ngIf="isBrowser">
    <full-calendar [options]="calendarOptions"></full-calendar>
 </ng-container>

推荐阅读