網站搜尋

typescript - Angular:使用相對路由的 navigate 方法路由到子組件無法工作


在這個 Stackblitz 中提供了使用的範例

這就是路由的結構方式

    RouterModule.forRoot([
      {
        path: 'login',
        component: LoginViewComponent,
        children: [
          { path: 'home', component: HomeViewComponent },
          { path: 'catalog/:id', component: CatalogViewComponent }
        ]
      },
      { path: '**', redirectTo: 'login' }
    ])
  ],

當我在登入元件時,我可以使用這個絕對路由前往首頁元件

this.navigate(['login/home']);

我也可以像這樣使用 navigateByUrl()

this.navigateByUrl(['login/home']);

但是我不明白如何使用 navigate() 進行相對路由

this.navigate(['home'], { relativeTo: this.route });
this.navigate(['/home'], { relativeTo: this.route });

這些方法都沒有路由到 homeComponent

答案#1

我沒有建立子路由,而是在路徑中使用了另一個相同名稱的路由:

app-routing.module.ts

{ path: "activity", component: ActivityComponent },
{ path: "activity/orders", component: OrdersComponent },

如果我在 activity 元件中,我通過以下方式導航到訂單:

this.router.navigate(["orders"], { relativeTo: this.route });`

在活動組件中的導入和建構子

import { Router, ActivatedRoute } from "@angular/router";
constructor(
  private router: Router,
  private route: ActivatedRoute,
) {