在Angular-2中使用Ui-route

时间:2016-11-03 12:01:31

标签: angular

我主要在angular-2中试验ui-router。我和你们所有人分享我的代码......

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 {}

工作正常..

但我担心的是,我想在不同页面中隔离此路由。就像我想制作另一个名为&#34; uirouting.ts&#34;我将编写所有与路由相关的代码,稍后我将其注入我的app.module.ts

任何人都可以指导我,我怎么能在静态中做到这一点。

提前致谢。

1 个答案:

答案 0 :(得分: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 {}

这是一个工作示例,来自hello world https://plnkr.co/edit/2vGIu0N03Qk8MsE6emWV?p=preview