And*_*ier 7 angular-universal angular
我需要获取我的Angular 2应用程序的完整基本URL(例如http:// localhost:5000或https://productionserver.com),以便我可以在应用程序的上下文中将其传递给第三方服务.应用程序的位置取决于它是开发,各种登台/测试环境还是生产,我想动态检测它,所以我不需要维护硬编码列表.
一个类似的问题已经提出,在过去,但答案(即使用window.location.hostname或window.location.origin属性的某些版本),只有当angular2应用程序正在被浏览器呈现工作.
我希望我的应用程序可以与Angular Universal一起使用,这意味着它需要在服务器端呈现,而无法访问像window.location这样的DOM对象.
任何想法如何实现这一目标?供参考,使用asp.net核心作为后端(使用默认的dotnet新角度模板).
chi*_*iya 19
我有点角度5和角度通用的工作代码
在server.ts中替换它
app.engine('html', (_, options, callback) => {
let engine = ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
{ provide: 'request', useFactory: () => options.req, deps: [] },
provideModuleMap(LAZY_MODULE_MAP)
]
});
engine(_, options, callback);
});
Run Code Online (Sandbox Code Playgroud)
在Angular方面,您可以使用以下代码获取主机
export class AppComponent {
constructor(
private injector: Injector,
@Inject(PLATFORM_ID) private platformId: Object
) {
console.log('hi, we\'re here!');
if (isPlatformServer(this.platformId)) {
let req = this.injector.get('request');
console.log("locales from crawlers: " + req.headers["accept-language"]);
console.log("host: " + req.get('host'));
console.log("headers: ", req.headers);
} else {
console.log('we\'re rendering from the browser, there is no request object.');
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我正在使用 server.ts ngExpressEngine:
\n\nimport { ngExpressEngine } from \'@nguniversal/express-engine\';\n\nconst {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require(\'./dist/server/main.bundle\');\n\n const {provideModuleMap} = require(\'@nguniversal/module-map-ngfactory-loader\');\n\n app.engine(\'html\', ngExpressEngine({\n bootstrap: AppServerModuleNgFactory,\n providers: [\n provideModuleMap(LAZY_MODULE_MAP)\n ]\n }));\nRun Code Online (Sandbox Code Playgroud)\n\n之后我可以在 location.service.ts 中使用:
\n\nconstructor(@Optional() @Inject(REQUEST) private request: any,\n @Optional() @Inject(RESPONSE) private response: any,\n @Inject(PLATFORM_ID) private platformId: Object)\n{\n if (isPlatformServer(this.platformId))\n {\n console.log(this.request.get(\'host\xe2\x80\x99)); // host on the server\n } else\n {\n console.log(document.location.hostname); // host on the browser\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
7667 次 |
| 最近记录: |