【问题标题】:Angular 6 Access Dependency Injector in renderModuleFactoryrenderModuleFactory 中的 Angular 6 访问依赖注入器
【发布时间】:2018-12-03 09:58:21
【问题描述】:

谁能指导一下如何访问依赖注入器来获取renderModuleFactory中的service实例?

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

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

【问题讨论】:

    标签: angular dependency-injection angular6 server-side-rendering angular-universal


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      相关资源
      最近更新 更多