Angular 2 - 在路由之间导航时音频播放器组件被破坏

问题描述 投票:0回答:1

我正在为音乐团体开发一个网站。它的组件之一是音频播放器。如果用户激活音频播放器,无论用户是否更改路径,我都需要激活它。

播放器位于父组件 (pages.component) 中,其余视图挂在该父组件中:

<div id="main-wrapper">
  <app-header></app-header>
  <div class="page-wrapper">
    <main>
      <router-outlet></router-outlet>
      <section id="player">
        <app-player></app-player>
      </section>
      <section id="mav-section">
        <app-icons-skirt *ngIf="_displaySkirtIcons"></app-icons-skirt>
        <app-banner-mav></app-banner-mav>
      </section>
    </main>
  </div>
  <app-footer></app-footer>
</div>

pages.routing 文件如下所示:

const routes: Routes = [
  {
    path: 'home', //A
    component: PagesComponent,
    children: [
      {
        path: '',
        component: HomeComponent,
      },
    ],
  },
  {
    path: 'projects',  //B
    component: PagesComponent,
    children: [
      {
        path: '',
        component: ProjectsComponent,
      },
      {
        path: ':id',
        component: DetailsViewComponent,
      },
    ],
  },
  {
    path: 'prizes', //C
    component: PagesComponent,
    children: [
      {
        path: '',
        component: EditionsLinksComponent,
      },
      {
        path: 'edition/:year/:id',
        component: DetailsViewComponent,
      },
      {
        path: 'edition/:year',
        component: EditionsComponent,
      },
    ],
  },
];

可以从路线 B 和 C 中包含的任何视图激活播放器。

例如,如果播放器在 B(项目)中激活,即使我们从 ProjectsComponent 导航到 DetailsViewComponent 或反之亦然,它仍保持活动状态。但如果我们从 B 导航到 C 或 A,它就会被破坏。

同样,如果我们在 C 中激活它,我们可以毫无问题地在 EditionsLinksComponent、DetailsViewComponent 和 EditionsComponent 之间导航。

我的问题是,无论用户选择的路线如何,我怎样才能让玩家保持活跃?

非常感谢您的宝贵时间。

angular routes nested-routes
1个回答
0
投票

在你的路由文件中,对于每条路由A\B\C,都定义了一个

PagesComponent
,尽管是相同的
PagesComponent
,但每次从A导航到B,从B导航到C时,它都会被破坏并重新初始化。 .等等

为了防止这种行为,你需要用

PagesComponent
定义一个路由,并使用A、B、C作为这个路由的子路由。

例子:

const routes: Routes = [
  {
    path: '',
    component: PagesComponent,
    children: [
      {
        path: 'home', // A
        component: HomeComponent,
      },
      {
        path: 'projects',  //B
        children: [
          {
            path: '',
            component: ProjectsComponent,
          },
          {
            path: ':id',
            component: DetailsViewComponent,
          },
        ],
      },
      {
        path: 'prizes', //C
        children: [
          {
            path: '',
            component: EditionsLinksComponent,
          },
          {
            path: 'edition/:year/:id',
            component: DetailsViewComponent,
          },
          {
            path: 'edition/:year',
            component: EditionsComponent,
          }
        ]
      }
    ]
  }
];
© www.soinside.com 2019 - 2024. All rights reserved.