![](/img/trans.png)
[英]Dependency Injection in Angular 2 Creates Multiple Instances while using Inline Injector and Constructor Injection
[英]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.