如何在Angular路由器中使用通配符作为部分路径?

时间:2017-08-22 17:21:52

标签: angular angular-routing

我有以下路由设置。

const routes: Routes = [
  { path: "submenu1", component: SubmenuComponent, outlet: "menus" },
  { path: "submenu2", component: SubmenuComponent, outlet: "menus" },
  { path: "submenu3", component: SubmenuComponent, outlet: "menus" },
  ...
];

我尝试使用通配符**以下列方式将开始子菜单匹配。可悲的是,我似乎没有那么匹配,也没有任何路由。

const routes: Routes = [
  { path: "submenu**", component: SubmenuComponent, outlet: "menus" },
  //{ path: "submenu1", component: SubmenuComponent, outlet: "menus" },
  //{ path: "submenu2", component: SubmenuComponent, outlet: "menus" },
  //{ path: "submenu3", component: SubmenuComponent, outlet: "menus" },
  ...
];

我该怎么做?

2 个答案:

答案 0 :(得分:1)

考虑制作1,2,3参数而不是路径字符串的一部分:submenu/1submenu/2等等。这样你的路线配置就可以

{ path: "submenu/:id", component: SubmenuComponent, outlet: "menus" },

以下是我的一个例子:

    RouterModule.forChild([
        {
            path: 'messages/:id',
            component: MessageComponent,
            outlet: 'popup'
        }
    ])

然后我以这种方式导航到它:

this.router.navigate([{outlets: { popup: ['messages', 7]}}]);

但是routerLink也可以。

结果是:http://localhost:3000/welcome(popup:messages/7)在浏览器地址栏中。

答案 1 :(得分:0)

以下情况如何?

const routes: Routes = [
  { path: "submenu1", component: SubmenuComponent, outlet: "menus" },
  { path: "submenu2", redirectTo: 'submenu'},
  { path: "submenu3", redirectTo: 'submenu'},
];

或者如果它不打扰你在app组件上放置一个路由器监听器:

ngOnInit() {

        if (isPlatformBrowser) {
            this.routerSubscription = this.router.events
                .filter(event => event instanceof NavigationEnd)
                .subscribe(() => {
                    if(this.router.url.startsWith('submenu'){
                        this.router.navigate(['submenu1']);
                    };
                });
        }
    }

    ngOnDestroy() {
        this.routerSubscription.unsubscribe();
    }