我试图通过使用路由器获取当前的路由器路径,但是当我这样做console.log(this.router.url)时返回"/",虽然我在"/ login".但是当我安慰整个this.router对象时,有一个url值为"/ login" 的属性.
这是来自app.component.ts的代码
export class AppComponent implements OnInit{
constructor(private router: Router) {}
ngOnInit(){
console.log(this.router);
}
}
Run Code Online (Sandbox Code Playgroud)
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 {}
Run Code Online (Sandbox Code Playgroud)
和FirstModule路由:
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 {}
Run Code Online (Sandbox Code Playgroud)
可以尝试Router使用Locationservice(https://angular.io/api/common/Location)及其方法path,而不是尝试使用(在导航生命周期的这一刻尚无法为您提供最终路线)。没有基本href的网址。相反,window.location.pathname不知道您的棱角玩具会为您提供路径,包括基本href。
import { Location } from '@angular/common';
export class AppComponent implements OnInit {
constructor(private location: Location) {}
ngOnInit(){
console.log(this.location.path());
}
}
Run Code Online (Sandbox Code Playgroud)
我有同样的问题.router.url返回斜杠,因为当ngOnInit在主应用程序组件上运行时,路由是根.这样做我得到了url的正确值.
this.router.events
.pipe(
filter(e => e instanceof NavigationEnd)
)
.subscribe( (navEnd:NavigationEnd) => {
console.log(navEnd.urlAfterRedirects);
});
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.但这并不适用于Angular Universal ......但仍然试图解决这个问题.
小智 1
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"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6840 次 |
| 最近记录: |