任何人都可以指导如何访问依赖注入器以获得renderModuleFactory中的 service 实例吗?
实际上,我在main.server文件中需要此文件,以为SSR返回正确的http状态代码。使用ASP.net,我们无法访问Response对象,因为在NodeJ情况下我们可以使用它。
也请看看ASP.Net Core 2.1 Angular SSR/Universal returning Http Status Code 404以了解上下文。
答案 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
}
});