[英]Angular 2 RC5 router.navigate not working
如果用戶是訪客,則我具有以下表達式:
this.router.navigate(['/intro']);
在我的app.component.ts ngOnInit()
方法中。
我的app.component.html具有<router-outlet></router-outlet>
但是當我以訪客身份訪問我的應用程序時,不會顯示IntroComponent
並且如果沒有/intro
,則URL將保持空白。
怎么了?
我的app.routes.ts
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{path:'intro',component: IntroComponent},
{path:'login',component: LoginComponent},
{path:'register', component: RegisterComponent}
];
像這樣更改您的路線:
const appRoutes: Routes = [
{ path: '', redirectTo: HomeComponent, pathMatch: 'full'}, //(redirectTo or component)
{path:'intro',component: IntroComponent},
{path:'login',component: LoginComponent},
{path:'register', component: RegisterComponent}
];
默認的pathMatch
策略是路由中的prefix
,因此帶有prefix
path: ''
實際上意味着每個路由。 所以everyroute被導航到HomeComponent
。
發生這種情況是因為從ngOnInit
調用this.router.navigate(['/intro'])
時,初始導航未完成。
有兩種解決方法:
解決方案1
在app.module.ts
您禁用初始導航
RouterModule.forRoot(appRoutes, { initialNavigation: false })
參考: router.navigate在組件的OnInit上靜默失敗
解決方案#2
如果您不想禁用初始導航,請使用setTimeout
允許初始導航完成。
setTimeout(() => this.router.navigate(['/intro']), 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.