Angular 路由器 url 返回斜杠 [英] Angular router url returns slash
问题描述
我正在尝试使用路由器获取当前路由器路径,但是当我执行 console.log(this.router.url)
时它返回/",尽管我在/登录".但是当我安慰整个 this.router
对象时,有一个属性 url
其值为/login".
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
,它将为您提供不带 base href 的 url.相反,window.location.pathname
不知道你的 angular 玩具,会给你包含 base 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());
}
}
这篇关于Angular 路由器 url 返回斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!