2016-11-03 73 views
2

我當時主要在angular-2上嘗試使用ui-router。我與大家分享我的代碼...在Angular-2中使用Ui路由

app.module.ts: -

import {UIRouterModule} from "ui-router-ng2"; 

let helloState = { name: 'hello', url: '/hello', component: HelloComponent }; 

let aboutState = { name: 'about', url: '/about', component: AboutComponent }; 

@NgModule({ 

    imports:[ 
    UIRouterModule.forRoot({ states: [ helloState, aboutState ], useHash: false }) 
    ], 

    declarations: [ AppComponent, DetailsComponent, HelloComponent, AboutComponent ], 

    bootstrap: [ AppComponent ] 

}) 

app.component.ts: -

@Component({ 

    selector: 'my-app', 

    template:` 
     <a uiSref="hello" uiSrefActive="active">Hello</a> 
     <a uiSref="about" uiSrefActive="active">About</a> 
     <ui-view></ui-view> 
     ` 
}) 

export class AppComponent {} 

它工作正常..

但我擔心的是,我想在不同的頁面中隔離此路由。就像我想做一個名爲「uirouting.ts」的頁面,我將寫所有的路由相關的代碼,後來我只是將它注入到我的app.module.ts

任何人都可以指導我,我該怎麼做靜態。

在此先感謝。

回答

0

創建一個管理你的狀態的子模塊。將其導入根應用程序模塊。

子模塊:

import { NgModule } from "@angular/core"; 
import { UIRouterModule } from "ui-router-ng2"; 
import { Hello, About } from "./components"; 

/** States */ 
let helloState = { name: 'hello', url: '/hello', component: Hello }; 
let aboutState = { name: 'about', url: '/about', component: About }; 

/** Root Application NgModule */ 

@NgModule({ 
    imports: [ 
    UIRouterModule.forChild({ 
     states: [helloState, aboutState] 
    }), 
    ], 
    declarations: [ Hello, About ], 
}) 
export class ChildModule {} 

路由模塊:

@NgModule({ 
    imports: [ 
    BrowserModule, 
    UIRouterModule.forRoot(), 
    ChildModule, 
    ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
class RootAppModule {} 

這裏有一個工作的例子,來自世界你好 https://plnkr.co/edit/2vGIu0N03Qk8MsE6emWV?p=preview

分叉