角路由器URL返回斜杠 [英] Angular router url returns slash
问题描述
我正在尝试使用路由器来获取当前的路由器路径,但是当我执行 console.log(this.router.url)
时,它将返回 /,虽然我在 /登录。
但是当我安慰整个 this.router
对象时,有一个属性 url
值 /登录。
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".
这是我来自app.component.ts的代码
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
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 {}
和FirstModule路由:
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 {}
推荐答案
而不是尝试使用 Router
(在导航生命周期的这一刻尚无法为您提供最终路线),您可以使用 Location
服务( https://angular.io/api/common/Location )及其方法 path
,它将为您提供不带基本href的网址。相反, window.location.pathname
不会意识到您的棱角玩具,会为您提供包括基本href在内的路径。
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());
}
}
这篇关于角路由器URL返回斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!