Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activated Route URL Always Empty

Consider the following service,

@Injectable()
export class SagasService {
    constructor(private route : ActivatedRoute, private router : Router ){
    router.events
        .filter(e => e instanceof NavigationStart)
        .subscribe(e=>{
            route.url.subscribe(a=>console.log(a[0].path));
        });
    }
}

Every time the route changes, the console.log() triggers. But, no matter what the route, the value is always "" (empty string).

What is wrong here?

like image 269
Code Whisperer Avatar asked Apr 17 '18 15:04

Code Whisperer


People also ask

How do I find the URL of a Activated route?

Steps to get current route URL in Angular. Import Router,NavigationEnd from '@angular/router' and inject in the constructor. Subscribe to the NavigationEnd event of the router. Get the current route url by accessing NavigationEnd's url property.

What is the difference between activated route vs activated route snapshot?

Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute . It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.

What is meant by activated route?

The ActivatedRoute is the API that holds observable data that you can use to react to events with. You can subscribe to specific observable properties to get data from it asynchronously. The ActivatedRoute also contains ActivatedRouteSnapshot.


2 Answers

The definition of the ActivatedRoute is:

Contains the information about a route associated with a component loaded in an outlet. An ActivatedRoute can also be used to traverse the router state tree.

That means that if you inject it in the service, you will get the ActivatedRoute from the AppComponent. Which would always have the path of "".

You can traverse the state tree to find the last activated route like

this.router.events.pipe(
 filter(event => event instanceof NavigationEnd),
 map(() => this.activatedRoute),
 map(route => {
   while (route.firstChild) {
    route = route.firstChild;
   }
   return route;
  }),
  map(route => route.url)
 )
.subscribe( // ... do something with the url)
like image 184
Tomasz Kula Avatar answered Sep 19 '22 14:09

Tomasz Kula


if you want to get the current URL, you can import the location import from angular/common as below

import {Location} from '@angular/common';

constructor(public location: Location ){ }

let currentUrl = this.location.path();

can be used in NavigationEnd subscriber

like image 28
Chinna M Avatar answered Sep 20 '22 14:09

Chinna M