Home > other >  Angular Router doesn't know URL
Angular Router doesn't know URL

Time:12-13

I want to do some logic with the url as a parameter when my app is loaded. I have an Ionic 5 project and in my app.component.ts file I have following code:

export class AppComponent {
  constructor(router: Router) {
    console.log(router.url);
  }
}

But in my console it logs '/' and not for example '/login'

How should this be properly done? Thank you very much!!!

CodePudding user response:

class MyComponent {
  constructor(route: ActivatedRoute) {
    const url: string = route.snapshot.url.join('');
  }

should do the trick. In case you just wanna access the information.

CodePudding user response:

You can subscribe the router events to get the url when navigate to a page.

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

export class AppComponent {   

  constructor(router: Router) {
    
  const routerSubscription = this.router.events
   .pipe(
     filter(event => event instanceof NavigationEnd)
    )
   .subscribe((event: NavigationEnd) => {
      const url = event.url;
    
      if (url != '/') {

        // To stop listen navigations
        routerSubscription.unsubscribe();

        // Your code
      }

    });
  }
}
  • Related