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()