如何在 Angular Universal 中获取完整的基本 URL(包括服务器、端口和协议)? [英] How to get full base URL (including server, port and protocol) in Angular Universal?

查看:30
本文介绍了如何在 Angular Universal 中获取完整的基本 URL(包括服务器、端口和协议)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取完整的基本 URL(例如 http://localhost:5000https://productionserver.com) 我的 Angular 2 应用程序,以便我可以将它传递给应用程序上下文中的第 3 方服务.应用的位置取决于它是开发、各种登台/测试环境还是生产,我想动态检测它,这样我就不需要维护一个硬编码列表.

I need to get the full base URL (e.g. http://localhost:5000 or https://productionserver.com) of my Angular 2 app so that I can pass it along to a 3rd party service in the context of the app. The app's location varies depending on whether it is development, various staging/testing environments, or production, and I'd like to detect it dynamically so I don't need to maintain a hard-coded list.

一个类似的问题已在过去,但答案(即使用某些版本的 window.location.hostname 或 window.location.origin 属性)仅在浏览器呈现 angular2 应用程序时有效.

A similar question has been posed in the past, but the answers (i.e. use some version of the window.location.hostname or window.location.origin property) only work when the angular2 app is being rendered by the browser.

我希望我的应用能够与 Angular Universal 一起使用,这意味着它需要在无法访问 window.location 等 DOM 对象的服务器端呈现.

I would like my app to work with Angular Universal, which means it needs to be rendered on the server side where there is no access to DOM objects like window.location.

任何想法如何实现这一点?作为参考,使用 asp.net core 作为后端(使用默认的 dotnet new angular 模板).

Any ideas how to accomplish this? For reference, using asp.net core as the back-end (using the default dotnet new angular template).

推荐答案

我有一些 angular 5 和 angular Universal 的工作代码

I have bit of working code with angular 5 and angular universal

在 server.ts 中替换这个

in server.ts replace this

app.engine('html', (_, options, callback) => {
    let engine = ngExpressEngine({
        bootstrap: AppServerModuleNgFactory,
        providers: [
            { provide: 'request', useFactory: () => options.req, deps: [] },
            provideModuleMap(LAZY_MODULE_MAP)
        ]
    });
    engine(_, options, callback);
});

在 Angular 方面,您可以使用以下代码获取主机

and in Angular side you can get host with below code

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

这篇关于如何在 Angular Universal 中获取完整的基本 URL(包括服务器、端口和协议)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆