Angular Universal和ngx可数据配置



我正试图将一些旧的应用程序转换为Angular universal(使用Angular 9(,但我在配置ngx dataable以处理服务器端渲染时遇到了问题。我遵循官方指导如何配置它https://github.com/swimlane/ngx-datatable/blob/master/docs/universal/server-side-rendering.md

但我对提供商的位置有问题

providers: [
{
provide: ScrollbarHelper,
useClass: ServerScrollBarHelper
},
{
provide: DimensionsHelper,
useClass: ServerDimensionsHelper
}
];

我的AppRoutingModule延迟加载其他具有loadChildren的子模块。我还使用SharedModule,其中定义了我的大多数客户端提供程序。

我发现,如果我在子模块中定义ServerScrollBarHelperServerDimensionsHelperthem,我只能访问它们,但问题是它们只能在Angular服务器端渲染时工作。我试着把它们放在AppServerModule提供者列表中,但后来就好像它们没有定义一样。

有这样的例子吗,或者有人知道我如何在不太改变应用程序结构的情况下轻松加载不同的服务器渲染和客户端渲染提供程序吗?

编辑:所以我把我的问题缩小到了延迟加载,因为使用layz加载模块,你不能从AppRoutingModule覆盖你的提供者,因为每个模块都使用自己的Injector。如果不从项目中删除懒惰加载,我仍然找不到解决方案,这听起来不太正确。

我目前对此问题的解决方案。

在每个懒惰加载的模块中,我注入了ServerScrollBarHelper&ServerDimensionsHelper,这样即使在延迟加载时我也可以访问它们。但我更改了他们的代码,使他们在服务器和浏览器中的行为有所不同。

import { Injectable, Inject, Injector, PLATFORM_ID } from '@angular/core';
import { Request } from 'express';
import { REQUEST } from '@nguniversal/express-engine/tokens';
import { DimensionsHelper } from '@swimlane/ngx-datatable';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
@Injectable()
export class ServerDimensionsHelper extends DimensionsHelper {
clientRqst;
constructor(@Inject(PLATFORM_ID) private platformId: Object, injectctor: Injector) {
super();
if (isPlatformServer(this.platformId)) {
this.clientRqst = injectctor.get(REQUEST);
}
}
getDimensions(element: Element): ClientRect {
if (isPlatformBrowser(this.platformId)) {
return super.getDimensions(element);
} else {
console.log(this.clientRqst.headers);
const width = parseInt(this.clientRqst.headers.cookie['CH-DW'], 10) || 1000;
const height = parseInt(this.clientRqst.headers.cookie['CH-DH'], 10) || 800;
const adjustedWidth = width;
const adjustedHeight = height;
return {
height: adjustedHeight,
bottom: 0,
top: 0,
width: adjustedWidth,
left: 0,
right: 0
};
}
}
}


import { ScrollbarHelper } from '@swimlane/ngx-datatable';
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
@Injectable()
export class ServerScrollBarHelper extends ScrollbarHelper {
width: number;
constructor(@Inject(DOCUMENT) document, @Inject(PLATFORM_ID) private platformId: Object) {
super(document);
this.width = 16; // use default value
}
getWidth(): number {
if (isPlatformBrowser(this.platformId)) {
return super.getWidth();
} else {
return this.width;
}
}
}

最新更新