0

Does anyone know how to get base url in Angular 4? For example: think I have that -> https://stackoverflow.com/questions/ask but I want to get only -> https://stackoverflow.com

I tried to get it like that :

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

But I got that error:

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 Answer 1

2

if you only want to get the origin of any path, you can just use window.location in ngOnInit instead of the constructor

ngOnInit() {
    this.baseUrl = window.location.origin
}
Sign up to request clarification or add additional context in comments.

16 Comments

I used it actually but I got an error when I press F5. Is tere any other way?
Which browser are you using? IE may have a problem with that function.. anyway, Replace the (platformLocation as any).location.origin with window.location.origin and tell me what browser you are using.
I am using chrome latest version.
After changing it, I got also "window is not defined" error.
You are trying to use this in client side right? Not the nodejs server right?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.