简体   繁体   中英

Angular 6 Access Dependency Injector in renderModuleFactory

Can anyone please guide how to access the dependency injector to get the a service instance in renderModuleFactory?

Actually I need this in main.server file to return proper http status code for SSR. With ASP.net we don't have access to Response object as we have it available in case of NodeJs.

Please also take a look at ASP.Net Core 2.1 Angular SSR/Universal returning Http Status Code 404 to understand the context.

I just now solved this by doing the following. This question is almost a year old, but maybe this is still helpful.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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