Ad Code

Ticker

6/recent/ticker-posts

How to get route URL in angular

 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?

Route URL

Answer:

  1.  If you want to route URL in string then use it: this.router.url (without window origin)

    Code: 

      import { ComponentOnInit } from '@angular/core';
      import { RouterActivatedRoute } from '@angular/router';

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

        constructor(private routerRouter,  private activeRouteActivatedRoute) { 
          
          console.log('Get Router URL:'this.router.url);
          
        }

        ngOnInit(): void {
        }

      }


    Output Log: 

    Get Router URL: /hero?name=johndoe#highlights
  2. If you want to route URL in segment then use: this.activeRoute.snapshot

    Code:

      import { ComponentOnInit } from '@angular/core';
      import { RouterActivatedRoute } from '@angular/router';

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

        constructor(private routerRouter,  private activeRouteActivatedRoute) { 
          this.activeRoute.queryParams.subscribe((qp=> {
            console.log('ActivatedRouteSnapshot:'this.activeRoute.snapshot);
          });
        }

        ngOnInit(): void {
        }

      }
        Browser Output: 

Route URL in angular browser output


Post a Comment

0 Comments

Ad Code

Responsive Advertisement