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

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

问题描述

我需要获取完整的基本URL(例如 http://localhost:5000

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核心作为后端(使用默认的dotnet新角度模板).

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

推荐答案

我有一些角度5和角度通用的工作代码

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天全站免登陆