首页 > 解决方案 > Angular:如何让父组件带有子路由以响应 URL 更改(包括子路由参数更改)?

问题描述

这是我目前的路线设置。(注意:当我们想看到 Schedule 屏幕时,主应用程序会加载 ScheduleComponent)ScheduleComponent 有一个<route-outlet>用于子路由的。

const routes: Routes = [
  {
    path: '',
    component: ScheduleComponent,
    data: {
      screenName: 'schedule',
    },
    children: [
      { path: '', redirectTo: 'ABC', pathMatch: 'full' },
      {
        path: ':service',
        component: ScheduleTilesContainerComponent,
        data: {
          screenName: 'schedule',
        },
      },
      {
        path: ':service/:year/:month/:day',
        component: ScheduleTilesContainerComponent,
        data: {
          screenName: 'schedule',
        },
      },
    ],
  },
];

在 ScheduleComponent 我有:

// this._route: ActivatedRoute (in constructor)
this._route.params.subscribe((params: Params) => {
 console.log('Schedule params: ', params);
}

在 ScheduleTilesContainerComponent 我有:

// this._route: ActivatedRoute (in constructor)
this._route.params.subscribe((params: Params) => {
 console.log('Tiles Container params: ', params);
}

情景 A:

当我们将其放入浏览器时:http://myserver.com/schedule 我们在控制台中看到:

Schedule params: {}
Schedule params: {service: "ABC"}
TileContainer params: {service: "ABC"}

然后用户交互触发: this._router.navigate(['schedule/ABC/2020/03/25']);

然后我们在浏览器地址栏看到:http://myserver.com/schedule/ABC/2020/03/25 我们在控制台看到这个:

TileContainer params: {service: "ABC", year: "2020, month: "03", day: "25"}

然后一个用户交互触发这个: this._router.navigate(['schedule/ABC/2020/03/11']); 然后我们在浏览器地址栏中看到:http://myserver.com/schedule/ABC/2020/03/11 我们在控制台中看到这个:

TileContainer params: {service: "ABC", year: "2020, month: "03", day: "11"}

问题1:为什么当我们navigation() 时,ScheduleComponent 没有看到params observable 流触发?

继续... 然后我单击 BACK 按钮: 我们在浏览器地址栏中看到:(http://myserver.com/schedule/ABC/2020/03/25正确的先前 URL)我们在控制台中看到:

TileContainer params: {service: "ABC", year: "2020, month: "03", day: "25"}

问题 2:为什么 ScheduleComponent 在这里也没有看到 params 可观察流触发?(应该是同一个问题)


情景 B

但是,如果这是我们进入屏幕的方式,那么 ScheduleComponent 确实获得了参数流!

直接把这个放到浏览器中:http://myserver.com/schedule/ABC/2020/03/25

Schedule params: {}
Schedule params: {service: "ABC", year: "2020, month: "03", day: "25"}
TileContainer params: {service: "ABC", year: "2020, month: "03", day: "25"}

然后用户交互触发: this._router.navigate(['schedule/ABC/2020/03/11']);

Schedule params: {service: "ABC", year: "2020, month: "03", day: "11"}
TileContainer params: {service: "ABC", year: "2020, month: "03", day: "11"}

如果我们单击 BACK 按钮,prev URL 会显示...我们在控制台中是这样的:

Schedule params: {service: "ABC", year: "2020, month: "03", day: "25"}
TileContainer params: {service: "ABC", year: "2020, month: "03", day: "25"}

问题 3:为什么 ScheduleComponent 的 param 流会看到这种变化?

问题 4:如何让我的 ScheduleComponent 始终看到 URL 更新?

标签: angularangular-routingangular-router

解决方案


推荐阅读