【发布时间】:2020-07-01 21:04:19
【问题描述】:
我们有一个 Angular Universal 应用程序,我们需要在运行服务器端时将值从 node.js 传递给 angular。我们通过在 server.ts 中使用以下代码解决了这个问题:
const theValue: TheType = nodeLogicToRetrieveValue();
app.engine('html', (_, options, callback) => {
let engine = ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP),
{ provide: 'theKey', useFactory: () => theValue, deps: [] }
]
});
engine(_, <any>options, callback)
});
在组件中,我们使用以下代码解析该对象:
if (isPlatformServer(this.platformId)) {
this.theValue = this.injector.get('theKey');
}
这很好用,但是 linting 会发出以下警告:
get 已弃用:从 v4.0.0 开始使用 Type
或 InjectionToken
我们尝试将其更改为使用 InjectionToken (new InjectionToken<TheType>('theKey')) 或类型而不是字符串,但这不起作用:
错误:StaticInjectorError(AppServerModule)[TheType]: StaticInjectorError(平台:核心)[TheType]: NullInjectorError:没有 TheType 的提供者!
是否只能通过字符串标记将值从节点传递到角度?
【问题讨论】:
标签: node.js angular angular-universal server-side-rendering