Angular router url returns slash

19,322

Solution 1

Instead of trying to use Router (which is not ready to give you final route at this moment of navigation lifecycle), you can use Location service (https://angular.io/api/common/Location) and its method path, which will give you the url without base href. On the contrary, window.location.pathname is not aware of your angular toys and will give you path including base href.

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

export class AppComponent implements OnInit {
  constructor(private location: Location) {}

  ngOnInit(){
    console.log(this.location.path());
  }

}

Solution 2

I have the same issue. The router.url returns a slash because when ngOnInit runs on the main app component, the route is the root. I got the correct value for the url by doing this.

  this.router.events
  .pipe(
    filter(e => e instanceof NavigationEnd)
  )
  .subscribe( (navEnd:NavigationEnd) => {
    console.log(navEnd.urlAfterRedirects);
  });

Hope that helps. This did not work with Angular Universal however... still trying to figure that out.

Solution 3

Type 1.We can also use window.location.pathname

Type 2.constructor(router: Router) { 

      router.events.subscribe((url:any) => console.log(url));

      console.log(router.url);  // to print only path eg:"/login"
}

Solution 4

if you want to get the url whenever you click on a new link/page you should use this:

this.router.events.subscribe((routerData) => {
      if(routerData instanceof ResolveEnd){ 
         if(routerData.url === 'your url'){
           //Do something
         }
    } 
})
Share:
19,322

Related videos on Youtube

sandum
Author by

sandum

Updated on October 26, 2022

Comments

  • sandum
    sandum over 1 year

    I'm trying to get the current router path by using Router, but when i do console.log(this.router.url) it returns "/", although i'm on the "/login". But when i'm consoling the entire this.router object, there is the property url which has value "/login".

    here is my code from app.component.ts

    export class AppComponent implements OnInit{
      constructor(private router: Router) {}
    
      ngOnInit(){
        console.log(this.router);
      }
    
    }
    

    app.module.routing.ts

    import {NgModule} from '@angular/core';
    import {PreloadAllModules, RouterModule, Routes} from '@angular/router';
    
    import {NotFoundComponent} from './not-found/not-found.component';
    import {AuthGuard} from './auth/auth-guard.service';
    
    const appRoutes: Routes = [
      { path: '', loadChildren: './first/first.module#FirstModule'},
      { path: 'login', loadChildren: './login/login.module#LoginModule'},
      { path: '404', component: NotFoundComponent, canActivate: [AuthGuard] },
      { path: '**', redirectTo: '/404'}
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(appRoutes, {preloadingStrategy: PreloadAllModules})],
      exports: [RouterModule]
    })
    export class AppModuleRouting {}
    

    and the FirstModule routing:

    import {NgModule} from '@angular/core';
    import {RouterModule, Routes} from '@angular/router';
    
    import {FirstComponent} from './first.component';
    import {AuthGuard} from '../auth/auth-guard.service';
    
    const firstRoutes: Routes = [
      { path: '', component: FirstComponent, canActivate: [AuthGuard], children:[
        { path: '', loadChildren: './content-container/container.module#ContainerModule' }
      ]}
    ];
    @NgModule({
      imports: [RouterModule.forChild(firstRoutes)],
      exports: [RouterModule]
    })
    export class FirstRoutes {}
    
  • Kazi
    Kazi about 5 years
    its return the same with the "/" @carecki
  • Rohit Parte
    Rohit Parte about 5 years
    It works perfectly for me in angular 7, Alternatively we can use JS core function console.log(window.location.href, this.router)
  • ironic_ollins
    ironic_ollins almost 5 years
    This is the solution to use if you don't want to wait (can be used in constructor too).
  • Shadi Alnamrouti
    Shadi Alnamrouti about 3 years
    Thank you. This is the only solution that worked for me on Angular 11.
  • gourabix
    gourabix over 2 years
    This is a great answer and should be part of accepted answer.
  • user1725382
    user1725382 over 2 years
    This worked great on Angular 9. Thanks for submitting!
  • com2ghz
    com2ghz almost 2 years
    No need to introduce race conditions with setTimeouts. Instead of that subscribe to the router events