2017-09-02 143 views
0

目前我是Angular的新手。我正在学习路由主题,但似乎停留在我想要在主路由中加载新路由的地步。我app.module看起来像如何在主要路线中加载新路线

import { NgModule }  from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 

import { AppComponent } from './app.component'; 
import {HttpModule} from '@angular/http'; 
import {RouterModule, Routes} from '@angular/router'; 
// COMPONENTS 
import {AppProduct} from './product.compnent'; 
import {AppFamily} from './family.component'; 

const appRoutes: Routes = [ 
    {path: 'Family', component: AppFamily}, 
    {path: 'Product', component: AppProduct} 
] 
@NgModule({ 
    imports:  [ BrowserModule, HttpModule, RouterModule.forRoot(appRoutes)], 
    declarations: [ AppComponent, AppFamily, AppProduct], 
    bootstrap: [ AppComponent ] 
}) 
export class AppModule { } 

app.component

import { Component } from '@angular/core'; 
import {IProducts} from './IProduct'; 
import {ProductService} from './products.service' 
// FAMILY IMPORTS 
import {IFamily} from './IFamily' 
import {familyService} from './family.service' 
@Component({ 
    selector: 'hello-world-app', 
    templateUrl: "app/app.component.html", 
    providers: [ProductService, familyService] 
}) 
export class AppComponent { 
    iproducts: IProducts[]; 
    familyMembers: IFamily[]; 
    constructor(
    private _product: ProductService, 
    private _family: familyService){ 
    } 
    ngOnInit():void{ 
    this._family.getAllFamilyMembers() 
    .subscribe(_successLog => { 
     this.familyMembers = _successLog; 
    }) 
    } 
} 

app.component.html

<ul> 
    <li> 
     <a [routerLink]="['/Product']"> 
      Product 
     </a> 
    </li> 
    <li> 
     <a [routerLink]="['/Family']"> 
      Family 
     </a> 
    </li> 
</ul> 
<router-outlet> 
</router-outlet> 

现在,当我为我的服务器一切顺利,除了我/产品和良好/家庭路线加载在<router-outlet></router-outlet>但我不希望导航菜单出现时,我访问/产品换句话说,我希望我的路线应加载在父路由没有子路由。 任何帮助,将不胜感激!

回答

1

你应该定义在appRoutes你的孩子不断模块,因为这:

{ path: '/childPath', 
component: ChildComponent, 
children: [ 
    {path: 'about', 
    loadChildren: './path/to/children.module#ModuleName'} 
    ] 
} 
+0

我会试试这个,谢谢! –

+0

查看更多:https://angular.io/guide/router#child-routing-component –

0

鹿先生的答案是懒加载正确的 - 但是,你不要总想做到这一点。如果你只想有子组件,你应该做的:

{ path: '/childPath', 
component: ChildComponent, 
children: [ 
    {path: 'about', 
    component: SecondChildComponent 
    ] 
} 

也就是说,延迟加载通常是优选的。