How to get route URL in angular
Description:
Suppose be mine browser URL is
http://localhost:4200/hero?name=johndoe#highlights
then how can i get full URL or in segment?
Answer:
- If you want to route URL in string then use it: this.router.url (without window origin)
Code:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
constructor(private router: Router, private activeRoute: ActivatedRoute) {
console.log('Get Router URL:', this.router.url);
}
ngOnInit(): void {
}
}
Output Log:
Get Router URL: /hero?name=johndoe#highlights
- If you want to route URL in segment then use: this.activeRoute.snapshot
Code:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {
constructor(private router: Router, private activeRoute: ActivatedRoute) {
this.activeRoute.queryParams.subscribe((qp) => {
console.log('ActivatedRouteSnapshot:', this.activeRoute.snapshot);
});
}
ngOnInit(): void {
}
}
Browser Output:
0 Comments