从子组件

时间:2016-03-19 08:59:55

标签: typescript angular angular2-routing

我已设置plnkr来演示我想要提出的问题

我在网络应用中有一些组件,

父组件App

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div class="main-container">
      <h2>This is the base. This div must be seen on app pages</h2>
      <a [routerLink]="['Home']"> Home </a> | 
      <a [routerLink]="['Users']"> Users  </a> | 
      <a [routerLink]="['Contact']"> Contact </a>
    </div>

    <router-outlet></router-outlet>
  `,
  directives: [ROUTER_DIRECTIVES]
})

@RouteConfig([
  {
    path: '/',
    name: 'Home',
    component: HomeComponent,
    useAsDefault: true

  },
  {
    path: '/users/...',
    name: 'Users',
    component: UsersComponent
  },
  {
    path: '/contact',
    name: 'Contact',
    component: ContactComponent
  }
])
export class App {

}

UsersComponent被加载到路由router-outlet的父控制器的/users,如下所示,

@Component({
  selector: 'my-app',
  template : `

    <div  *ngFor="#page of pages">
      <a [routerLink]="[page.name]">
        {{page.slug}}
      </a>
    </div>

    <router-outlet></router-outlet>
  `
})
@RouteConfig([
  {path : '/', name: 'Main', component: MainRoute, useAsDefault: true}  
])
export class UsersComponent{
  /**
  * some methods to configure the routes,
  */
}

UsersComponent已为用户动态配置路由

例如。 /alex/john等,

由于路径来自子组件,路径看起来像example.com/users/alexexample.com/users/john等。但我希望路径为example.com/alexexample.com/john

我也希望将与每个用户关联的组件加载到父router-outlet。在此处的示例中,router-outlet App以便我可以删除用户列表。

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

以下是我对您的配置的看法:Plunker

<强> 1。定义您的App RouteConfig就像这样

@RouteConfig([
  {
    path: '/',
    name: 'Home',
    component: HomeComponent,
    useAsDefault: true

  },
  {
    path: '/:user',
    name: 'User',
    component: PersonComponent
  },
  {
    path: '/users',
    name: 'Users',
    component: UsersComponent
  },
  {
    path: '/contact',
    name: 'Contact',
    component: ContactComponent
  }
])

<强> 2。从router.config

中删除<router-outlet>UsersComponent

不要通过RouteData发送用户数据,因为您必须提前为每个用户定义路由,这不是必需/有效的。

@Component({
  selector: 'my-app',
  template : `

    <div  *ngFor="#page of pages">
      <a [routerLink]="['User', {user: page.name}]">
        {{page.slug}}
      </a>
    </div>
  `,
  providers : [PagesService]
})
export class UsersComponent{
  pages = [];

  constructor(private pgSvc: PagesService, router: Router) {
  }
}

第3。构建您的服务以发送特定用户的数据

<强> 4。更新您的PersonComponent以适应这些变化。

@Component({
  selector : 'person',
  template : `
  <div class="person-container">
    <h3>Person selected : <strong> {{data.get['user']}} </strong></h3>
  </div>
  `
})
class PersonComponent {
  constructor(public data: RouteParams) {

   // call your service here to get the user specific data by using 
    let userName = data.get('user');

   // yourService.getUserData(userName);
  }
  routerCanReuse(next, prev) {
    return false;
  }
}