我无法使用 angular 通用的文档注入

I cannot use the document injection with angular universal

我尝试使用 DOM 的文档 属性 来删除和添加 类 到 html 并管理一些 CSS 属性,但是当我执行 ng run app:serve-ssr 命令时出现以下问题:

这是我的代码,它是一个名为 app-initializer 的提供程序中的服务,这是提供程序,这是它在 AppModule 中导入的方式。

@Injectable({
  providedIn: 'root',
})
export class ThemeService {
 constructor(@Inject(DOCUMENT) private document: Document) {}

 private loadCss(href: string, id: string): Promise<Event> {
    return new Promise((resolve, reject) => {
      const style = this.document.createElement('link');
      style.rel = 'stylesheet';
      style.href = href;
      style.id = id;
      style.onload = resolve;
      style.onerror = reject;
      this.document.head.append(style);
    });
  }
}

AppInitializerProvider

import { APP_INITIALIZER } from '@angular/core';
import { ThemeService } from './utils/services';

export const AppInitializerProvider = {
  provide: APP_INITIALIZER,
  useFactory: (themeService: ThemeService) => () => {
    return themeService.loadTheme();
  },
  deps: [ThemeService],
  multi: true,
};

App module

// ....
providers: [AppInitializerProvider]
// ....

应用程序版本:

  1. Angular CLI:11.2.7
  2. 节点:14.16.0
  3. Angular: 11.2.8
  4. 在 Google Chrome 和 Microsoft Edge
  5. 中测试

请尝试使用 appendChild,服务器端可能不支持 append DOM

this.document.head.appendChild(style);

您也可以使用 Renderer2,在操作 angular

中的 DOM 个元素时推荐使用它
this.renderer.appendChild(this.document.head, style);