Flowbite 和 Angular 18 SSR 出现文档未定义错误

问题描述 投票:0回答:1

第一次在堆栈溢出和非常初级的开发人员上发帖,如果提出问题的方式有一些错误,请抱歉。

我正在尝试将 Flowbite 库与 Angular 18 SSR 一起使用。

flowbite.service.ts:

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable({
  providedIn: 'root',
})
export class FlowbiteService {
  constructor(@Inject(PLATFORM_ID) private platformId: any) {}

  loadFlowbite(callback: (flowbite: any) => void) {
    if (isPlatformBrowser(this.platformId)) {
      import('flowbite').then((flowbite) => {
        callback(flowbite);
      });
    }
  }
}

app.components.ts:

export class AppComponent implements OnInit {
  title = 'dashboard-simplon';

  ngOnInit(): void {
    initFlowbite();
  }
}

我尝试在其中使用 Flowbite 的组件之一:

import { Component, Input, OnInit } from '@angular/core';
import { FlowbiteService } from '../../../../services/flowbite.service';

@Component({
  selector: 'app-dashboard-progress-bar',
  standalone: true,
  imports: [],
  templateUrl: './dashboard-progress-bar.component.html',
  styleUrl: './dashboard-progress-bar.component.scss',
  providers: [FlowbiteService],
})
export class DashboardProgressBarComponent implements OnInit {
  @Input() title = 'test';

  constructor(private flowbiteService: FlowbiteService) {}

  ngOnInit(): void {
    this.flowbiteService.loadFlowbite((flowbite) => {
      // Your custom code here
      console.log('Flowbite loaded', flowbite);
    });
  }
}

我已按照此处的安装步骤进行操作:https://flowbite.com/docs/getting-started/angular/ 以及这个github问题:https://github.com/themesberg/flowbite/issues/800没有成功。

我知道问题来自于 Flowbite 尝试使用 DOM API 中的

document
,但我不明白可以采取什么措施来解决该问题。

angular flowbite angular-ssr
1个回答
0
投票

问题的解决方案是仅在浏览器上运行 flowbite。

推荐的方法是使用

afterNextRender()
,它只会在浏览器上回调:

export class DashboardProgressBarComponent implements OnInit {
  @Input() title = 'test';

  constructor(private flowbiteService: FlowbiteService) {
    afterNextRender(() => {
      // this only runs in the browser
      this.flowbiteService.loadFlowbite((flowbite) => {
        console.log('Flowbite loaded', flowbite);
      });
    });
  }
}

此外,根据您的需要,您可以简单地禁用 SSR。

© www.soinside.com 2019 - 2024. All rights reserved.