How do i get the url (window.location) of the current request in Angular 5?
Asked Answered
F

3

6

How do i get the url of the current request in Angular 5?

I tried a couple of solutions i found online but nothing seems to work. - $window - Wrapping native window in WindowRef example

I've been looking for this all morning, but kinda new to Angular and get lost in the different examples online targeting different versions of Angular.

UPDATE: I'm using TypeScript

Thanks

Firth answered 4/12, 2017 at 11:48 Comment(3)
What do you call "current request" exactly?Lucilius
You want to current url in page right?Outwash
The url in the address bar of the browser is what i'm after. But with the answers below i figured it out already.Firth
D
8

If you want the angular solution you could use this.

import { Router } from '@angular/router';

constructor(private router:Router) {}

someMethod(){
  console.log(this.router.url)
}

else you could use the standard window solution

window.location.href returns the href (URL) of the current page.

Douglasdouglashome answered 4/12, 2017 at 13:35 Comment(3)
I'm now using the wrapper approach and got it to work. But i will try this as well. Saves me a wrapper class.Firth
I forgot to mention im using TypeScript and in typescript window is undefined.Firth
Router only returns "local" routes to the app, (not sure if this is the right lingo) myhost.com/myapp/api is not included in the location of router. So i stuck with the WindowRef wrapper method.Firth
T
1

If you want to use window.location.href in your component in TypeScript, you will need to add the following declaration with your other imports:

declare let window;

A short write up on this is available here in this blog post or answers like these.

Truthful answered 26/2, 2018 at 18:2 Comment(0)
H
0

To fetch the current URL in the browser address bar you can use window.location.href.You don't need an angular wrapper for getting the current URL.

Hopeh answered 4/12, 2017 at 12:12 Comment(1)
If i try it like that it says window is undefined. Using the wrapper approach i got it to work. ThanksFirth

© 2022 - 2024 — McMap. All rights reserved.