Angular 2不同的模块相同的路由

时间:2017-10-10 09:50:25

标签: angular angular2-routing

我有两条主要路线,都加载了相同的子模块。有没有办法在子模块上有两个具有相同名称的路由,它们相对于主路径加载两个不同的组件。

主要路线

export const ROUTES: Routes = [{
    path: 'first',
    loadChildren: './features/common#CommonModule',
    canActivate: [AppAuthGuard]
}, {
    path: 'second',
    loadChildren: './features/common#CommonModule',
    canActivate: [AppAuthGuard]
}]

现在我期待公共模块有类似这样的路由

export const routes = [{
        path: 'list', component: FirstListComponent, pathMatch: 'full' }
    },{
        path: 'list', component: SecondListComponent, pathMatch: 'full' }
    }]

所以,我想要像

这样的东西
  • 如果路由是 first / list ,则应加载 FirstListComponent
  • 如果路由是 second / list ,则应加载 SecondListComponent

我知道路线的顺序很重要。并且提出的方法是不可能的。任何人都可以建议任何可能的方法来实现这一目标。

2 个答案:

答案 0 :(得分:1)

请设置这样的路径

export const routes = [{
        path: 'first/list', component: FirstListComponent, pathMatch: 'full' }
    },{
        path: 'second/list', component: SecondListComponent, pathMatch: 'full' }
    }]

答案 1 :(得分:0)

这对我有用,并且更简单:

应用程序路由

const routes: Routes = [
  {
    path: 'mobile',
    loadChildren: './view/mobile/mobile.module#MobileModule',
    canActivate: [MobileGuardService],
    data: {
      preload: false
    }
  },
  {
    path: 'desktop',
    loadChildren: './view/desktop/desktop.module#DesktopModule',
    canActivate: [DesktopGuardService],
    data: {
      preload: false
    }
  },
  {
    path: 'error',
    loadChildren: './view/error/error.module#ErrorModule',
    data: {
      preload: false
    }
  },
  {
    path: '',
    redirectTo: window.innerWidth < 768 ? `/mobile/etc/etc/etc` : `/desktop/etc/etc/etc`,
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: window.innerWidth < 768 ? `/mobile/etc/etc/etc` : `/desktop/etc/etc/etc`
  }
];

Mobile Guard

@Injectable({
  providedIn: 'root'
})
export class MobileGuardService implements CanActivate {

  constructor(
    private router: Router
  ) {
  }

  canActivate() {
    if (window.innerWidth >= 768) {
      this.router.navigate(['/']).then();
      return false;
    }
    return true;
  }

}

Desktop Guard

@Injectable({
  providedIn: 'root'
})
export class DesktopGuardService implements CanActivate {

  constructor(
    private router: Router
  ) {
  }

  canActivate() {
    if (window.innerWidth < 768) {
      this.router.navigate(['/m/']).then();
      return false;
    }
    return true;
  }

}

我这样做是因为redirectTo造成了警卫队的问题:(

:)