繁体   English   中英

renderModuleFactory中的Angular 6访问依赖注入器

[英]Angular 6 Access Dependency Injector in renderModuleFactory

谁能指导如何访问依赖注入器以在renderModuleFactory中获取服务实例?

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

也请看看ASP.Net Core 2.1 Angular SSR / Universal返回Http Status Code 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
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM