Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

routing - Angular router url returns slash

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 {}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...