5

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

4 Answers4

7

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.

yusuf
  • 1,233
  • 1
  • 15
  • 29
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.

Nate Anderson
  • 18,334
  • 18
  • 100
  • 135
-1

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.

Ankit Kapoor
  • 1,615
  • 12
  • 18
-1
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{

    constructor(private location: Location) {}

    public back(): void {
      this.location.back()
    }

}
Oram
  • 1,589
  • 2
  • 16
  • 22
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – Dwhitz Mar 19 '19 at 07:52