使用Angular 4获取基本URL

时间:2018-09-06 18:44:02

标签: angular

有人知道如何在Angular 4中获取基本网址吗? 例如:认为我有-> https://stackoverflow.com/questions/ask 但我只想得到-> https://stackoverflow.com

我试图那样做:

constructor(private http: Http, private platformLocation: PlatformLocation) {
            this.baseUrl = (platformLocation as any).location.origin;
    }

但是我遇到了这个错误:

An unhandled exception occurred while processing the request.
NodeInvocationException: Cannot read property 'origin' of undefined
TypeError: Cannot read property 'origin' of undefined
at new AppSettingsService (D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\main-server.js:3028:50)
at _createClass (D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\vendor.js:20473:17)
at _createProviderInstance$1 (D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\vendor.js:20441:26)
at initNgModule (D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\vendor.js:20395:13)
at new NgModuleRef_ (D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\vendor.js:21503:9)
at Object.createNgModuleRef (D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\vendor.js:21487:12)
at NgModuleFactory_.module.exports.NgModuleFactory_.create (D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\vendor.js:24768:25)
at D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\vendor.js:15453:61
at ZoneDelegate.module.exports.ZoneDelegate.invoke (D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\vendor.js:85786:26)
at Object.onInvoke (D:\Projects\CH.AdminClient\CH.AdminClient\ClientApp\dist\vendor.js:14830:37)
Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance+<InvokeExportAsync>d__7.MoveNext()

1 个答案:

答案 0 :(得分:2)

如果您只想获取任何路径的原点,则可以使用 ngOnInit中的window.location而不是构造函数中

ngOnInit() {
    this.baseUrl = window.location.origin
}