2016-08-30 228 views
0

我有以下表達式,如果用戶是來賓:角2 RC5 router.navigate不工作

this.router.navigate(['/intro']); 

在我app.component.ts ngOnInit()方法。

我app.component.html有<router-outlet></router-outlet>

但是當我進入我的應用程序作爲嘉賓,不顯示IntroComponent和URL沒有/intro保持爲空。

怎麼了?

我app.routes.ts

const appRoutes: Routes = [ 
    { path: '', component: HomeComponent }, 
{path:'intro',component: IntroComponent}, 
{path:'login',component: LoginComponent}, 
{path:'register', component: RegisterComponent} 
]; 
+0

您正在使用什麼版本的Angular?你有配置的路線嗎?您是否正確導入它們(取決於您擁有的版本)?我們需要更多信息來幫助您解決問題 –

+0

路由已配置,RC.5。我添加了我的app.routes.ts,HomeCOmponent已加載儘管我正在使用this.router進行導航以引導 – TheUnreal

+0

請將一個最簡單的示例粘貼到一個plunker中。 – mxii

回答

0

這是因爲從調用ngOnInitthis.router.navigate(['/intro'])時沒有完成初始導航。

有兩種方法來解決這個問題:

解決方案#1

app.module.ts禁用初始導航

RouterModule.forRoot(appRoutes, { initialNavigation: false }) 

編號:router.navigate failing silently on OnInit of component

解決方案#2

如果您不想禁用初始導航,請使用setTimeout來完成初始導航。

setTimeout(() => this.router.navigate(['/intro']), 1) 
1

改變你的路線是這樣的:

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所以path: ''prefix意味着幾乎everyroute。所以每個人都被導航到HomeComponent