渲染模块工厂中的 Angular 6 Access Dependency Injector



任何人都可以指导如何访问依赖注入器以获取renderModuleFactory中的服务实例吗?

实际上,我需要在main.server文件中使用它来为SSR返回正确的http状态代码。有了 ASP.net 我们就无法访问响应对象,因为我们在 NodeJs 的情况下可以使用它。

另请查看 ASP.Net Core 2.1 Angular SSR/Universal 返回 Http 状态代码 404 以了解上下文。

我刚才通过执行以下操作解决了这个问题。这个问题已经快一年了,但也许这仍然有帮助。

export { AppServerModule } from './server/app-server.module';
// Add this line so that you can provide this token in your aspnet-rendering script as shown below.
// The reason we have to export the service here is so you can get access to the same copy used by the Angular code.
export { StatusCodeService as StatusCodeServiceToken } from './server/services/http-response.service';
const { AppServerModule, AppServerModuleNgFactory, LAZY_MODULE_MAP, StatusCodeServiceToken } = require('./../server/main.js');
export default createServerRenderer(async params => {
// Instantiate your service manually.
const statusCodeService = new StatusCodeService();
const options = {
document,
url: params.url,
extraProviders: [
provideModuleMap(LAZY_MODULE_MAP),
// Provide your instance as a value provider.
{ provide: StatusCodeServiceToken, useValue: statusCodeService }
]
};
const html = AppServerModuleNgFactory
? await renderModuleFactory(AppServerModuleNgFactory, options)
: await renderModule(AppServerModule, options);
return {
html,
// Then you can retrieve the value because you have the instance.
statusCode: statusCodeService.statusCode
}
});

最新更新