如何在Angular Universal中获取完整的基本URL(包括服务器,端口和协议)?

And*_*ier 7 angular-universal angular

我需要获取我的Angular 2应用程序的完整基本URL(例如http:// localhost:5000https://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)

  • 看起来这可以工作:https://github.com/DmitriyIvchenko/angular/blob/10a8e5056b9c66aa7006b02e45c13fd2bae24350/project/application/src/app/modules/core/services/http-request-data/http-request-data. ts (3认同)
  • 当我在本地运行它时它工作正常,但在服务器上它给出了 No provider request 的错误!. 有解决方案吗?我正在研究 Angular 4 (2认同)

Iva*_*nik 5

现在我正在使用 server.ts ngExpressEngine

\n\n
import { 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    }));\n
Run Code Online (Sandbox Code Playgroud)\n\n

之后我可以在 location.service.ts 中使用:

\n\n
constructor(@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}\n
Run Code Online (Sandbox Code Playgroud)\n

  • 这对我来说不起作用。`this.request.get('host')` 始终返回 127.0.0.1:4000 (3认同)