2017-04-26 21 views
-2

我有一個路由器插座在我的app.html .problem是我有3(後,管理員,addposts)組件除了app.component .in我的帖子組件我有下拉菜單onece我點擊下拉我想加載addposts和url應該看起來像這個post/addposts。任何想法如何做到這一點Angular 2 Routes

這是我app.routes.ts

const routes: Routes = [ 

     { path: '', redirectTo: 'main', pathMatch: 'full'}, 
     { path: 'main', component:AdminBodyComponent }, 
     { path: 'admin', component:AdminComponent }, 
     { path: 'posts',component:PostsComponent}, 
     { path: 'addposts',component:AddPostComponent}]; 
+0

請加標點符號,正確的大寫和空格你的問題。另外,請在標題中提出實際問題。 – 2017-04-26 04:18:32

回答

1

通過先安裝路由器:NPM安裝路由器

import { Routes, RouterModule } from '@angular/router'; 
 

 

 
export const router: Routes = [ 
 
    { path: '', redirectTo: 'main', pathMatch: 'full'}, 
 
    { path: 'main', component:AdminBodyComponent }, 
 
    { path: 'admin', component:AdminComponent }, 
 
    { path: 'posts',component:PostsComponent}, 
 
    { path: 'addposts',component:AddPostComponent}]; 
 

 
export const routes: ModuleWithProviders = RouterModule.forRoot(router); 
 
step2: 
 
inject into your .ts file 
 
constructor(
 
    private router:Router, 
 
    ... 
 
) 
 
step3: 
 
this.router.navigate(['/addposts']); 
 

 
step4: 
 
<base href="/">

,如果你想使用特定的路由器去爲這個 第四步:

1

Oprion 1:

如果你可以添加一個錨標記,這將是最簡單的。

<a routerLink="/addposts" routerLinkActive="active">Add Post</a> 

選項2:

按以下3個簡單的步驟。

步驟1:導入角路由器

import { Router } from '@angular/router'; 

步驟2:使用依賴注入注入的值

constructor(
     private router:Router, 
     ... 
) 

步驟3:調用引導()中的點擊內部事件

this.rou ter.navigate([ '/ addposts']);

1

我假設你想導航到不同的頁面,因爲你想要路由到post/addposts。然後你可以改變你的路徑

{ path: 'post/addposts',component:AddPostComponent}]; 

我可能是錯的,你可能想改爲使用多個router-outlet。

0

首先通過安裝路由器:NPM安裝路由器

import { Routes, RouterModule } from '@angular/router'; 
 

 

 
export const router: Routes = [ 
 
    { path: '', redirectTo: 'main', pathMatch: 'full'}, 
 
    { path: 'main', component:AdminBodyComponent }, 
 
    { path: 'admin', component:AdminComponent }, 
 
    { path: 'posts',component:PostsComponent}, 
 
    { path: 'addposts',component:AddPostComponent}]; 
 

 
export const routes: ModuleWithProviders = RouterModule.forRoot(router); 
 
step2: 
 
inject into your .ts file 
 
constructor(
 
    private router:Router, 
 
    ... 
 
) 
 
step3: 
 
this.router.navigate(['/addposts']);
如果要使用特定的路由器去爲這個 第四步 :

+0

請刪除你的答案,你已經提供了兩個確切的答案;)謝謝! – Alex