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?
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?
The new V3 router has a url property.
this.router.url === '/login'
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
Inject Location
to your component and read location.path();
You need to add You need to add ROUTER_DIRECTIVES
somewhere so Angular can resolve Location
.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
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);
});
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:
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"
}
To get the route segments:
import { ActivatedRoute, UrlSegment } from '@angular/router';
constructor( route: ActivatedRoute) {}
getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }
import { Router } from '@angular/router';
constructor(router: Router) {
console.log(router.routerState.snapshot.url);
}
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);
}
}
);
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());
}
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.
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);
}
});
}
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
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.
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
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
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);
}
}
);
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.
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;
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
}
});
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"
}
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
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>
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!
router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
this.currentUrl = e.url;
}
});
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)
}
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
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
});
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;
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
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);
});
}
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';
this.router.events.subscribe((val) => {
const currentPage = this.router.url; // Current page route
const currentLocation = (this.platformLocation as any).location.href; // Current page url
});
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);
});
}
import {ActivatedRoute} from '@angular/router';
constructor(private route:ActivatedRoute){
console.log(this.route.routeConfig.path);
}
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'];
});
}
}
in component file:
import {ActivatedRouteSnapshot} from '@angular/router';
constructor(state: ActivatedRouteSnapshot) {
console.log(state.path)
}
in routeing file:
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
});
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') { ... }
}
If we want to know the url / path of every route change in a component where it's commonly rendered in every route.
currentPage: String = '';
constructor(private _router: Router) {
this._router.events.subscribe((val) => {
if(val instanceof NavigationEnd) {
this.currentPage = this._router.url;
}
})
}