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

时间:2018-06-24 19:02:59

标签: angular dependency-injection angular6 serverside-rendering angular-universal

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

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

也请看看ASP.Net Core 2.1 Angular SSR/Universal returning Http Status Code 404以了解上下文。

1 个答案:

答案 0 :(得分:0)

我现在通过执行以下操作解决了这个问题。这个问题已经快一年了,但这也许还是有帮助的。

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
  }
});