angular - 用于 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 { }
现在我不知道我应该修改哪些其他文件才能制作:
- app.module.ts 仅与平台无关的代码(可以导入到服务器/浏览器模块的共享模块)
- server.module.ts 仅服务器端代码(可以 ssr'ed)
- browser.module.ts 包含所有平台无关代码和浏览器代码(例如 fullcalendar 模块
解决方案
我把事情复杂化了。为了避免在服务器端使用浏览器 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>
推荐阅读
- mariadb - mariabackup:空备份文件
- flutter - 如何在拖动时获取触摸位置
- angular - 角度6 scss错误
- django - 为什么 SECURE_SSL_REDIRECT 总是设置为 True?
- haskell - 如何检查 Text.XML.Cursor 中节点的内容?
- assertj - 如何在 AssertJ 中链接多个 assertThat 语句
- node.js - 如何在环回 3 中需要时自动迁移?
- ios - Face ID userFallback在iOS swift中不起作用
- mysql - mysql 0000-00-00 00:00:00 转换为空
- javascript - 三.js子忽略父变换