对具有不同输出的不同路由使用相同的组件

use same component for different routes with different output

在我的应用程序中,我喜欢为医生创建一个主控 (CRUD)。我有一个用于创建、编辑和列表的医师组件。用于查看它的单独组件。我想URL的喜欢

physician/create

physician/list

physician/edit/3

所以我用 children

创建了路线
const routes: Routes = [
{
  path: 'physician',
  children: [
    { path: 'list', component: PhysicianComponent },
    { path: 'create', component: PhysicianComponent },
    { path: 'update/:id', component: PhysicianComponent },
    { path: 'view/:id', component: PhysicianViewComponent }
  ]
}

对于创建、更新和列表,我想使用相同的组件,但使用组件内部的某些条件输出不同 class

您可以只有一个组件并根据 URL 处理要执行的操作,但我认为这不是最佳解决方案。

如果我是你,我会为每个页面创建不同的组件,使用它们自己的模板和它们自己的功能。

如果您不想这样做,您将不得不在模板和组件逻辑中使用大量条件。例如:

constructor(private router: Router) {}

get route() { return this.router.url; }

onFormButtonClick() {
  if (this.router.url.endsWith('physician/create')) { /* ... */ }
  else if (this.router.url.includes('physician/edit/')) { /* ... */ }
}

在你的组件中

<ng-container *ngIf="route.endsWith('physician/create')">...</ng-container>
<ng-container *ngIf="route.includes('physician/edit/')">...</ng-container>

是的,通过使用 ActivatedRoute 服务,您可以检查路由参数和路由器 url 以检查要应用的条件,但这很难维护。想象一下,您只需更改 url 或更改参数名称,因此您需要在组件中更改它。另一种方法是向每条路线添加数据 属性 类似标志的东西,并根据该标志应用特定条件-

const routes: Routes = [
{
  path: 'physician',
  children: [
    { path: 'list', component: PhysicianComponent, data: { kind: 'list' } },
    { path: 'create', component: PhysicianComponent, data: { kind: 'create' } },
    { path: 'update/:id', component: PhysicianComponent, data: { kind: 'update' } },
    { path: 'view/:id', component: PhysicianViewComponent, date: { kind: 'view' } }
  ]
}

组件:

ngOnInit() {
  this.activeRoutedService.data.subscribe(data => {
    switch (data.kind) {
      //....
    }
  });
}

您可以设置路由数据并获取组件中的数据以显示不同的输出:

{ path: 'list', component: PhysicianComponent, data: { viewOption: 'list' } },
{ path: 'create', component: PhysicianComponent, data: { viewOption: 'create' } },
{ path: 'update/:id', component: PhysicianComponent, data: { viewOption: 'update' } },

在您的组件中,从 ActivatedRoute.snapshot.data

获取数据
constructor(private route: ActivatedRoute) { }

ngOnInit() {
    this.viewOption = this.route.snapshot.data.viewOption;
}

您可以使用 ngSwitch

在你的控制器中,决定路线是什么

whichView: string;
constructor(private router: Router) {
  if (this.router.url.endsWith('physician/create')) {
    this.whichView = 'create';
  } else if (this.router.url.endsWith('physician/edit')) {
    this.whichView = 'edit'
  } else {
    this.whichView = 'view'
  }
}

在视图中:

<container-element [ngSwitch]="whichView">
  <some-element *ngSwitchCase="create">...</some-element>
  <some-element *ngSwitchCase="edit">...</some-element>
  <some-other-element *ngSwitchCase="update">...</some-other-element>
  <some-element *ngSwitchDefault>...</some-element>
</container-element>