0

I'm trying to get the current URL or route in my web application, I figured out the way to do this in angular is using the following code

```
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable({
providedIn: 'root'
})
export class IncService {

public mainPage: any;

constructor(private router: Router) {

 //get current route
 router.events.subscribe(endUrl => {
   if(endUrl instanceof NavigationEnd ){
     this.mainPage = endUrl.url;
         console.log(this.mainPage); //works perfectly
   }
 });

  console.log(this.mainPage); //does not work, outputs undefined

}

}

```

I expect console.log(this.mainPage) to output the current route eg /home but I get 'undefined' instead.

NB I want 'this.mainPage' to be available in anywhere in my class as the current URL not only in the subscribe()

  • Is it `undefined` always or only the first time when the constructor is called ? – ashish.gd Apr 22 '19 at 08:29
  • Try to provide a handler, See https://angular.io/guide/observables#defining-observers – sachq Apr 22 '19 at 08:33
  • Welcome to the asynchronous world! Check the duplicate for some possible solutions. Hopefully one fits for you. – AT82 Apr 22 '19 at 10:47

1 Answers1

0

You can move console.log(this.mainPage); to complete () =>{} like this and you can not use anywhere in class because subscribe called asynchronous.

//get current route
 router.events.subscribe(endUrl => {
   if(endUrl instanceof NavigationEnd ){
     this.mainPage = endUrl.url;
         console.log(this.mainPage); //works perfectly
   }
 },
 ()=>{
     console.log(this.mainPage); //does not work, outputs undefined
 });
}
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62