1

Is there a way to get the initial route's url(the route that happens when you reload the page).

I want to apply a css style to an element based on it.

So far I injected ActivatedRoute console logged it like so:

  constructor(private router: Router, private actRoute: ActivatedRouteSnapshot) {
     console.log(actRoute);

Chrome then shows an ActivatedRoute object containing a _routerState property which has a snapshot with the url that I want.

The problem is that when I do: console.log(actRoute._routerState); I get an error because the router state property doesn't exist.

Am I missing something here? Because just writing actRoute.url or actRoute.snapshot.url just gives an empty path.

Thanks.

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

2 Answers2

0

Use Router and following will give you the complete path:

this.router.routerState.snapshot.url
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46
0

I figured out how to view only the first, initial, route.

In my app.component.ts I created a local variable event and then set it equal to the this.router.events.subscribe function.

After I was done with the router I just called this.even.this.event.unsubscribe().

Here's my code:

event;

export class AppComponent implements OnInit {
  constructor(private router: Router) { }

  ngOnInit() {
    this.event = this.router.events.subscribe((e) => {
      if (e instanceof NavigationEnd) {
        console.log(e);

        // Doing stuff with the router

        this.event.unsubscribe();
      }
    });
  }
}

And my imports:

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