【问题标题】:I cannot use the document injection with angular universal我不能使用带有角度通用的文档注入
【发布时间】:2023-03-12 18:31:01
【问题描述】:

我尝试使用 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,
};

应用模块

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

应用版本:

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

【问题讨论】:

  • @Inject(DOCUMENT) private document: Document 出于某种原因(不要问我)document 应该是any 类型,所以@Inject(DOCUMENT) private document: any

标签: angular typescript dom angular-universal angular11


【解决方案1】:

尝试改用appendChildappend 可能在服务器端 DOM 上不受支持

this.document.head.appendChild(style);

您也可以使用Renderer2,在从角度操作 DOM 元素时推荐使用此方法

this.renderer.appendChild(this.document.head, style);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多