747

The current docs only talk about getting route params, not the actual route segments.

For example, if i want to find the parent of current route, how is that possible?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
pdeva
  • 43,605
  • 46
  • 133
  • 171
  • 51
    `window.location.pathname` – Dennis Hackethal Oct 06 '16 at 22:47
  • 6
    @dchacke the problem with `window.location` is that if in the future, they want to implement server-side rendering, they will face some difficulties since `window` does not exist on the Node.js server, but they need to use the Angular standard methods to access the route and they'll be fine both on server and browser. – Mohammad Kermani Mar 30 '20 at 09:25

41 Answers41

838

The new V3 router has a url property.

this.router.url === '/login'
Victor96
  • 9,102
  • 1
  • 13
  • 13
  • 5
    I use this code and i am getting this url in string variable but when i try to print in console .log it is not printing this.fullUrl = this.router.url console.log(this.fullUrl); // not printing – vijay gupta Oct 28 '16 at 12:47
  • 3
    Look at using the new router active feature Dashboard – Victor96 Nov 14 '16 at 16:28
  • this works with the current [angular2-seed](https://github.com/angular/angular2-seed) (which is currently on angular 2.2.1). – Benny Bottema Dec 19 '16 at 20:00
  • 2
    This isn't really a great solution because if you want to see if the current route is the root `/` if there is a query string you'll end up with `/?q=something` which would break this. – The Muffin Man Feb 09 '17 at 19:44
  • This is incredibly useful for creating persistent buttons that route somewhere, and return home when clicked again. No need to create a service to follow the state if the router does it for you! – Z. Bagley Jun 09 '17 at 22:43
  • 66
    this is useless when you are navigating with Hash strategy, the url is always "/" – Ninja Coding Aug 01 '17 at 17:27
  • 5
    @NinjaCoding I am using Hash strategy and I am getting just "/". How can i get route url with Hash ? – Murtuza Aug 03 '18 at 03:00
  • 30
    @Murtuza here is a solution: `this.router.events.filter((event: any) => event instanceof NavigationEnd).subscribe(event => { console.log('this is what your looking for ', event.url); });` . Make sure you import `import { Router, NavigationEnd } from '@angular/router'; ` – Gel Dec 14 '18 at 05:38
  • now is 2019 - I use hash strategy - and it works - return right url e.g. `"/login"` – Kamil Kiełczewski Jul 25 '19 at 19:19
  • 4
    @Murtuza 's comment/answer is correct, just remember that now to be able to use filter you have to wrap it in pipe so it will be: `this.router.events.pipe( filter((event: any) => event instanceof NavigationEnd) ).subscribe(event => { console.log('this is what your looking for ', event.url); });` and you have to import pipe too. – alexOtano Oct 24 '19 at 02:00
  • 8
    @Murtuza pointed me in the right direction. However, not need to filter, just listen for NavigationEnd ```this.router.events.subscribe((event) => { event instanceof NavigationEnd ? console.log(event): null })``` – Matthew Pitts Nov 08 '19 at 23:12
  • This does not solve issue. Question was about route segments, not full url. For example you need to store last url with query parameters and restore the url, then you would need to extract query parameters from the string, then store the url. That solution is way too complex. There are other options to solve this – Imants Volkovs Mar 16 '20 at 08:37
  • 1
    Just piggybacking on Matthew Pitts' answer, I used this code to perform some actions whenever the route changed: --- `this.router.events.subscribe((event: NavigationEnd | null) => { if (event instanceof NavigationEnd) { console.log(event.url); } });` – Michael F. Aug 27 '20 at 10:42
  • 1
    This is how it worked for me: `this.router.events.pipe(filter((event: NavigationEnd) => event instanceof NavigationEnd)).subscribe(event => { console.log('this is what your looking for ', event.url); });` ` – PinguinoSod Mar 31 '21 at 20:34
  • Is there not official proper way from Angular to returns the route as level array. I could process the url by my self. For example split by `'/'` etc. But I can't believe that Angular has no functions for that. Use case: Implement a method like `isDashboard` which checks the first level route and is also true on routes like: `dashboard/one`, `dashboard/two/three`, etc. Yes I could use something like `router.url.startsWith('/dashboard/')`, but is there really not official better way from Angular? ... – Domske Apr 19 '21 at 08:31
  • There is also the need to subscribe to it so that we can reload the component correctly – Royer Adames Jun 07 '22 at 16:46
  • Some people say this does not work for hash strategy, but for me it does work. I am getting the url and not just the "/". Has things changed in the last years? I am using Angular 14. – Danie Aug 17 '23 at 06:59
  • If you want to always listen to the route and also get the first loaded route, you can use this code. `private router = inject(Router); currentRoute = signal(''); this.router.events.subscribe((event: any) => { this.currentRoute.set(event?.routerEvent?.url); // this is the current route you need }); ` – joseph chikeme Aug 23 '23 at 18:57
277

Angular RC4:

You can import Router from @angular/router

Then inject it:

constructor(private router: Router ) {

}

Then call it's URL parameter:

console.log(this.router.url); //  /routename
Rafique Mohammed
  • 3,666
  • 2
  • 38
  • 43
lowcrawler
  • 6,777
  • 9
  • 37
  • 79
  • 5
    The extra clarity about how to import the router itself is very helpful. Could you clarify if it would be different if you were using a custom Router? – kbpontius Jan 25 '17 at 00:44
  • 1
    That would certainly depend on the 'custom-ness' of the custom Router. (sorry this wasn't a particularly helpful comment -- if you have a specific question, I'd suggest making a new question and referencing this answer) – lowcrawler Jan 25 '17 at 12:07
  • 111
    I used this solution, but I always get this " / ". Does anyone know why? – Marcio M. Jul 25 '17 at 17:59
  • 4
    Angular Dependency Injection relies on the TypeScript sugar syntax, so when you declare private _router: Router in the constructor signature, a property _router is automatically created in the current class instance with the Router injected. This statement this.router = _router; is just an overhead to me, as you'd have two reference to the same object instance (in that case, the Router). – Andrea Alhena Jan 30 '18 at 17:21
  • 1
    @Marcio M. It might be because the router has not actually reached that state, even though the URL shows different. For example, if your look at the router.url in a guard service. location.path() as mentioned in the answers will give you the url, no matter what the router state is. – Daniel van Niekerk Jan 31 '18 at 10:58
  • @MarcioM.See Ninja Coding's answer above: "this is useless when you are navigating with Hash strategy, the url is always "/"". What strategy are you using? – bogdan.rusu Jan 23 '19 at 14:58
  • I'm not using the Hash strategy, and I always get "/" as the result.... – Mike Gledhill Jan 17 '23 at 11:12
74

Inject Location to your component and read location.path(); You need to add ROUTER_DIRECTIVES somewhere so Angular can resolve Location. You need to add import: [RouterModule] to the module.

Update

In the V3 (RC.3) router you can inject ActivatedRoute and access more details using its snapshot property.

constructor(private route:ActivatedRoute) {
  console.log(route);
}

or

constructor(private router:Router) {
  router.events.subscribe(...);
}

See also Angular 2 router event listener

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 4
    that gives me the 'url' path. how do i find the 'route names' so i can pass them in an array on to the `navigate` method along with the (appended) name of child route i want to navigate to. – pdeva Jan 04 '16 at 19:55
  • I see. I also don't find this satisfactory. I haven't tried it myself but maybe the `MyTrackingService` explained in http://stackoverflow.com/a/34548656/217408 would allow to access these values. – Günter Zöchbauer Jan 04 '16 at 19:59
  • Route names are gone now. – Günter Zöchbauer Jun 22 '16 at 15:15
  • 7
    @GunterZochbauer is there a way to get the _requested_ route _before_ it's activated? For example, if I want to store the _requested_ route inside of a `canActivate()` method, so that I can redirect to a "login" page, and then redirect _back_ to the original route after the user authenticates? – Eugene Ananin Jul 09 '16 at 20:52
  • 1
    Can't you do that with a canActivate guard? – Günter Zöchbauer Jul 12 '16 at 04:44
  • @Yevgeny Refer http://jasonwatmore.com/post/2016/12/08/angular-2-redirect-to-previous-url-after-login-with-auth-guard for your requirement – Anil Agrawal Oct 30 '17 at 07:11
  • isn't listening to router events too expensive? – Imants Volkovs Mar 16 '20 at 08:38
  • 1
    No idea why you think listening to these events could be expensive. Router event are quite infrequent and all this listening does is storing the callback in a list to be called when a router event happens. I'd say if you care about performance you're better off checking for unnecessary server requests and DOM re-render. – Günter Zöchbauer Mar 16 '20 at 11:30
  • No idea why you think listening to these events could be expensive. Router event are quite infrequent and all this listening does is storing the callback in a list to be called when a router event happens. I'd say if you care about performance you're better off checking for unnecessary server requests and DOM re-render. – Günter Zöchbauer Mar 16 '20 at 11:31
72

Use this

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

constructor(private router: Router) {
    router.events.filter(event => event instanceof NavigationEnd)
        .subscribe(event => {
            console.log(event);
        });
}

And in main.ts import

import 'rxjs/add/operator/filter';

EDIT

Modern way

import {filter} from 'rxjs/operators';

router.events.pipe(
    filter(event => event instanceof NavigationEnd)
)
    .subscribe(event => {
        console.log(event);
    });
Vlad
  • 7,997
  • 3
  • 56
  • 43
  • 23
    Is this really the recommended way to do something as simple as checking where the current URL is pointing? I'm not arguing against you on this one. However, I noticed that the routing thing is a source of many changes, updates, confusions etc. I was kind of expecting that *ActivatedRoute* would be used primarily for this, not *Router*. Am I missing the complexity of the issue, perhaps? – DonkeyBanana May 10 '18 at 10:45
  • I'm referring to [ActivatedRoute](https://angular.io/api/router/ActivatedRoute) in the official docs. – DonkeyBanana May 10 '18 at 10:49
  • 2
    No need for any at least here, the router exports the "RouterEvent" type that is extended by the other router events - https://angular.io/api/router/RouterEvent – chrismarx Nov 07 '19 at 13:51
  • 1
    @chrismarx fixed – Vlad Nov 07 '19 at 14:57
  • @DonkeyBanana Actually, if you're dealing with nested modules which contain their own routes, then yes. In fact, using nested modules and routers (which is what the Angular Team even recommends) this is the *only* way to get the actual URL of the current route, all other methods will simply return `/`. – Eagerestwolf Apr 10 '20 at 04:31
  • 1
    this works fine. but when i start the app, first time at that time no event is fired. this works when the route change – Sunil Garg Apr 22 '20 at 07:14
  • 1
    @SunilGarg You could use the `startsWith` rxjs operator `startWith(this.router.url),` – Barry Jones Oct 22 '21 at 19:11
  • For correct typing `filter((event): event is NavigationStart => event instanceof NavigationStart),` – Jonathan May 28 '23 at 17:50
54

For those who are still looking for this. On Angular 2.x there are a few ways of doing it.

constructor(private router: Router, private activatedRoute: ActivatedRoute){

   // string path from root to current route. i.e /Root/CurrentRoute
   router.url 

    // just the fragment of the current route. i.e. CurrentRoute
   activatedRoute.url.value[0].path

    // same as above with urlSegment[]
   activatedRoute.url.subscribe((url: urlSegment[])=> console.log(url[0].path))

   // same as above
   activatedRoute.snapshot.url[0].path

   // the url fragment from the parent route i.e. Root
   // since the parent is an ActivatedRoute object, you can get the same using 
   activatedRoute.parent.url.value[0].path
}

References:

  1. https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html
  2. https://angular.io/docs/ts/latest/api/router/index/Router-class.html
  3. https://angular.io/docs/ts/latest/guide/router.html
Severin Klug
  • 733
  • 5
  • 9
n4nd0_o
  • 2,929
  • 1
  • 15
  • 9
44

for new router >= RC.3

Best and a simple way to do this is!

import { Router } from '@angular/router';
constructor(router: Router) { 
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  // to print only path eg:"/login"
}
Rajath M S
  • 1,092
  • 2
  • 18
  • 28
31

To get the route segments:

import { ActivatedRoute, UrlSegment } from '@angular/router';

constructor( route: ActivatedRoute) {}

getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }
ttugates
  • 5,818
  • 3
  • 44
  • 54
31
import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}
Char
  • 2,073
  • 8
  • 28
  • 45
21

To reliably get the full current route you can use this

this.router.events.subscribe(
  (event: any) => {
    if (event instanceof NavigationEnd) {
      console.log('this.router.url', this.router.url);
    }
  }
);
18

An easier way if you can't access router.url (for instance if you used skipLocationChange) you can use the following :

import { Location } from '@angular/common';    
constructor(private readonly location: Location) {}
    
ngOnInit(): void {
  console.log(this.location.path());
}
Yohan Dahmani
  • 1,670
  • 21
  • 33
16

You can try with

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

constructor(private router: Router, private activatedRoute:ActivatedRoute) {
console.log(activatedRoute.snapshot.url)  // array of states
console.log(activatedRoute.snapshot.url[0].path) }

Alternative ways

router.location.path();   this works only in browser console. 

window.location.pathname which gives the path name.

Jose G Varanam
  • 767
  • 8
  • 19
14
import { Router, NavigationEnd } from "@angular/router";

constructor(private router: Router) {
  // Detect current route
  router.events.subscribe(val => {
    if (val instanceof NavigationEnd) {
      console.log(val.url);
    }
  });
}
Hamza
  • 469
  • 3
  • 9
13

The native window object works fine as well

console.log('URL:' + window.location.href);
console.log('Path:' + window.location.pathname);
console.log('Host:' + window.location.host);
console.log('Hostname:' + window.location.hostname);
console.log('Origin:' + window.location.origin);
console.log('Port:' + window.location.port);
console.log('Search String:' + window.location.search);

NOTE: DO NOT USE THIS IN SERVER SIDE RENDERING

Sanket Berde
  • 6,555
  • 4
  • 35
  • 39
7

I had the same problem using

this.router.url

I get the current route with query params. A workaround I did was using this instead:

this.router.url.split('?')[0]

Not a really nice solution, but helpful.

Ant T.
  • 306
  • 5
  • 9
7

short version if you have Router imported then you can simply use some thing like

this.router.url === "/search"

else do the following

1) Import the router

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

2) Declare its entry in constructor

constructor(private router: Router) { }

3) Use its value in your function

yourFunction(){
    if(this.router.url === "/search"){
        //some logic
    }
}

@victor answer helped me, this is the same answer as him but with a little detail, as it might help someone

Mateen
  • 1,631
  • 1
  • 23
  • 27
7

to get current router in angular 8 just do this

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

then inject it in constructor like

constructor(private route: ActivatedRoute){}

if you want get current route then use this route.url

if you have multiply name route like /home/pages/list and you wanna access individual then you can access each of like this route.url.value[0].path

value[0] will give home, value[1] will give you pages and value[2] will give you list

Hans
  • 2,448
  • 2
  • 24
  • 30
abubakkar tahir
  • 737
  • 1
  • 11
  • 13
7

This applies if you are using it with an authguard

this.router.events.subscribe(event => {
        if(event instanceof NavigationStart){
            console.log('this is what your looking for ', event.url);  
         }
       } 
   );
Steve Nginyo
  • 303
  • 3
  • 12
6

With angular 2.2.1 (in an angular2-webpack-starter based project) works this:

export class AppComponent {
  subscription: Subscription;
  activeUrl: string;

  constructor(public appState: AppState,
              private router: Router) {
    console.log('[app] constructor AppComponent');
  }

  ngOnInit() {
    console.log('[app] ngOnInit');
    let _this = this;
    this.subscription = this.router.events.subscribe(function (s) {
      if (s instanceof NavigationEnd) {
        _this.activeUrl = s.urlAfterRedirects;
      }
    });
  }

  ngOnDestroy() {
    console.log('[app] ngOnDestroy: ');
    this.subscription.unsubscribe();
  }
}

In AppComponent's template you can use e.g. {{activeUrl}}.

This solution is inspired by RouterLinkActive's code.

Adrian
  • 3,321
  • 2
  • 29
  • 46
  • this is a good answer b/c if you have a wild card route that redirects back to /home event.url is not enough to match the /home route it will actually show the route that does not exist. event.urlAfterRedirects will print the actual end route. ty. – Ian Poston Framer Apr 15 '19 at 22:35
6

WAY 1: Using Angular: this.router.url

import { Component } from '@angular/core';

// Step 1: import the router 
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    //Step 2: Declare the same in the constructure.
    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        // Do comparision here.....
        ///////////////////////////
        console.log(this.router.url);
    }
}

WAY 2 Window.location as we do in the Javascript, If you don't want to use the router

this.href= window.location.href;
Trilok Pathak
  • 2,931
  • 4
  • 28
  • 34
5

You can use in the .ts file

import { Route, Router, NavigationStart } from '@angular/router';

constructor(private router: Router) {}

this.router.events.subscribe(value => {
      if (value instanceof NavigationStart) {
        console.log(value) // your current route
      }
    });
Chirag
  • 413
  • 1
  • 6
  • 16
5

simplest way

import { Router } from '@angular/router';
constructor(router: Router) { 
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  <---------- to get only path eg:"/signUp"
}
Naeem Bashir
  • 1,937
  • 20
  • 17
4

angular 2 rc2

router.urlTree.contains(router.createUrlTree(['/home']))
nadav
  • 552
  • 5
  • 11
4

You can use ActivatedRoute to get the current router

Original Answer (for RC version)

I found a solution on AngularJS Google Group and it's so easy!

ngOnInit() {
  this.router.subscribe((url) => console.log(url));
}

Here's the original answer

https://groups.google.com/d/msg/angular/wn1h0JPrF48/zl1sHJxbCQAJ

Khaled Al-Ansari
  • 3,910
  • 2
  • 24
  • 27
  • Has been changed as of rc.2, as `url` now is no longer the URL and a string, but a `ComponentInstruction`. – Martin C. Jul 01 '16 at 10:59
4

Here is what is working for me in Angular 2.3.1.

location: any;

constructor(private _router: Router) { 

      _router.events.subscribe((data:any) => { this.location = data.url; });

      console.warn(this.location);  // This should print only path e.g. "/home"
}

The data is an object and we need the url property contained in that object. So we capture that value in a variable and we can use that variable in our HTML page as well. For example, I want to show a div only when user is on Home page. In this case, my router url value will be /home. So I can write a div in the following way:

<div *ngIf="location == '/home'">
This is content for the home page.
</div>
Devner
  • 6,825
  • 11
  • 63
  • 104
4

I was facing the problem where I needed the URL path when the user is navigating through the app or accessing a URL (or refreshing on a specific URL) to display child components based on the URL.

More, I want an Observable that can be consumed in the template, so router.url was not an option. Nor router.events subscription because routing is fired before the component's template is initialized.

this.currentRouteURL$ = this.router.events.pipe(
     startWith(this.router),
     filter(
         (event) => event instanceof NavigationEnd || event instanceof Router
     ),
     map((event: NavigationEnd | Router) => event.url)
);

Hope it helps, good luck!

Andrew Radulescu
  • 1,862
  • 13
  • 21
4

router.events.subscribe(e => {
      if (e instanceof NavigationEnd) {
        this.currentUrl = e.url;
      }
    });
3

In Angular2 Rc1 you can inject a RouteSegment and then pass it into the .navigate() method:

constructor(private router:Router,private segment:RouteSegment) {}

ngOnInit() {
  this.router.navigate(["explore"],this.segment)
}
Martin Zeitler
  • 1
  • 19
  • 155
  • 216
Arpit Agarwal
  • 3,993
  • 24
  • 30
3

For your purposes you can use this.activatedRoute.pathFromRoot.

import {ActivatedRoute} from "@angular/router";
constructor(public activatedRoute: ActivatedRoute){

}

With the help of pathFromRoot you can get the list of parent urls and check if the needed part of the URL matches your condition.

For additional information please check this article http://blog.2muchcoffee.com/getting-current-state-in-angular2-router/ or install ng2-router-helper from npm

npm install ng2-router-helper
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
3

this is simple, in angular 2 you only need to import the Router library like this:

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

Then in the constructor of the component or service you must instantiate it like this:

constructor(private _router: Router) {}

Then in any part of the code, either in a function, method, construct, whatever:

      this._router.events
        .subscribe(
            (url:any) => {
                let _ruta = "";
                url.url.split("/").forEach(element => {
                    if(element!=="" && _ruta==="")
                        _ruta="/"+element;  
                });
                console.log("route: "+_ruta); //<<<---- Root path
                console.log("to URL:"+url.url); //<<<---- Destination URL                    
                console.log("from URL:"+this._router.url);//<<<---- Current URL
            }); 
eberlast
  • 160
  • 2
  • 7
3

To find the parent of the current route, you can obtain the UrlTree from the router, using relative routes:

var tree:UrlTree = router.createUrlTree(['../'], {relativeTo: route});

Then to get the segments of the primary outlet:

tree.root.children[PRIMARY_OUTLET].segments;
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
3

As of now, I'm getting my path as follows -

this.router.url.subscribe(value => {
    // you may print value to see the actual object
    // console.log(JSON.stringify(value));
    this.isPreview = value[0].path === 'preview';
})

Where, router is an instance of ActivatedRoute

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
3

This one is tested on Angular 11

constructor(private router: Router) {
  this.router.events
   .pipe(filter((event: any) => event instanceof NavigationEnd))
   .subscribe((event: any) => {
     this.currentRoute = event.url;
     console.log(event);
   });
 }
Ketan
  • 5,861
  • 3
  • 32
  • 39
Mohan Dere
  • 4,497
  • 1
  • 25
  • 21
  • This works, but what to do if I need to have it earlier, in Component Init event? And there this.router.url is '/'... :( I need this to operate with collapsing / expanding 3rd party menu and NavigationEnd, even NavigationStart is too late to affect the menu layout... – Alexander Jun 15 '21 at 20:03
  • for correct typing `filter((event): event is NavigationStart => event instanceof NavigationStart),` – Jonathan May 28 '23 at 17:52
3

For me the accepted answer did not work when accessing the current route within AuthGuardService implements CanActivate since the route isn't fully processed yet. I answered the same question here (https://stackoverflow.com/a/68541653/1479486) but if you just want to copy paste from here, this is my solution:

const finalUrl = this.router.getCurrentNavigation()?.finalUrl;   
const isLoginPage = finalUrl?.root.children['primary'].segments[0]?.path === 'login'; 
Tim Rasim
  • 655
  • 7
  • 20
2
this.router.events.subscribe((val) => {
   const currentPage = this.router.url; // Current page route
  const currentLocation = (this.platformLocation as any).location.href; // Current page url
});
2

If you need to access the current url, usually you have to wait for NavigationEnd or NavigationStart to do something. If you just subscribe to the router events the subscription will output many events in the route lifecycle. Instead, use an RxJS operator to only filter for the Event you need. The beneficial side effect of this is now we have stricter types!

constructor(private router: Router) {
    router.events.pipe(
      filter(ev => (ev instanceof NavigationEnd))
    ).subscribe((ev: NavigationEnd) => {
      console.log(ev.url);
    });
}

steveblue
  • 455
  • 4
  • 19
  • for correct typing `filter((event): event is NavigationStart => event instanceof NavigationStart),` – Jonathan May 28 '23 at 17:52
2
import {ActivatedRoute} from '@angular/router';
constructor(private route:ActivatedRoute){
    console.log(this.route.routeConfig.path);
}
NoDiced
  • 33
  • 1
  • 8
  • this only gives the first segment. you need to iterate through `route.children[0]` and take the `routeConfig.path` value from each segment. If you're using auxiliary routes the `outlet` property will tell you which outlet you're in and you'd need special handling for that. – Simon_Weaver Nov 30 '19 at 22:09
1

this could be your answer, use params method of activated route to get paramter from URL/route that you want to read, below is demo snippet

import {ActivatedRoute} from '@angular/router'; 
@Component({
})
export class Test{
constructor(private route: ActivatedRoute){
this.route.params.subscribe(params => {
             this.yourVariable = params['required_param_name'];
        });
    }
}
Vinod
  • 1,234
  • 3
  • 21
  • 37
1

in component file:

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

constructor(state: ActivatedRouteSnapshot) {
    console.log(state.path)
}

in routeing file:

enter image description here

mojtaba ramezani
  • 1,461
  • 16
  • 15
1

If you want to always listen to the route and also get the first loaded route, you can use this code.

private router = inject(Router);
currentRoute = signal<string>('');


this.router.events.subscribe((event: any) => {
      this.currentRoute.set(event?.routerEvent?.url); // this is the current route you need
    }); 
joseph chikeme
  • 184
  • 1
  • 12
0

I was facing the problem when i want to change the background according to the route. But it works only when i navigate through the website, not when i refresh the page.

In router.events.subscribe(), this is events.url when i navigate, this.router.url when i refresh.

Now it works :

import { ActivatedRoute, Router, NavigationStart } from '@angular/router';

constructor(private router: Router) {}

public ngOnInit() {
    this.router.events.subscribe((events:any) => {
        let theme = '';
        if (events instanceof NavigationStart) { theme = events.url; }
        else { theme = this.router.url; }
        
        if(theme === '/videos') { ... }
}
0

If we want to know the url / path of every route change in a component where it's commonly rendered in every route.

  1. Subscribe to the every route event.
  2. If the subscribed value is the instance of NavigationEnd, then the currentPage url is router.url.

currentPage: String = '';
constructor(private _router: Router) {
    this._router.events.subscribe((val) => {
        if(val instanceof NavigationEnd) {
            this.currentPage = this._router.url;
        }
    })
}
Tejesh Palagiri
  • 729
  • 4
  • 9