后退按钮在同一页面上创建多个组件

Back button creating multiple components on the same page

In my Angular 6 app, there are certain pages that do not respond appropriately when I click "back". The site will instead spawn multiple components, instead of redirecting the user back to the single component they just went to.

For the faulty components, I made the component.html page be one single line like such as:

// home-page.component.html home

and

// admin-page.component.html admin

And then the component.ts page is using default code as well.

On my app.component.html, I just have the following:

<router-outlet></router-outlet>

Now when I go on the home page (via <a routerLink="/admin">Admin></a>), I correctly see this (more or less)in my HTML when I inspect the site. And note this is just the RESULTING HTML that appears when I right click - view page source etc... I know my routing is setup correctly as this whole thing works in Google Chrome, but not in Firefox.

<html> <head>...</head> <body> <app-root> <router-outlet> <app-admin-page>admin</app-admin-page> </router-outlet> </app-root> </body> </html>

But when I now press "back", I see the below

<html> <head>...</head> <body> <app-root> <router-outlet> <app-home-page>home</app-home-page> <app-admin-page>admin</app-admin-page> </router-outlet> </app-root> </body> </html>

When I pressed "back", it should of DELETED the <app-admin-page>admin</app-admin-page> and just kept the new <app-home-page>home</app-home-page>, but it keeps both. I can then press "forward" and then it'll have 3 components. Any ideas what is going on here? Note that if I'm on the 'admin' page and click the 'home' link (which does a routerLink thing), it works correctly. It's just the back button messing up.

您正在混合使用子组件和路由。对于任何特定组件,您应该使用一个或另一个。

<router-outlet></router-outlet> 标签之间不应定义任何组件。

注意你上面的代码:

          <router-outlet>
              <app-admin-page>admin</app-admin-page>
          </router-outlet>

所以要么像这样将两个组件都显示为子组件:

      <app-root>
         <app-home-page>home</app-home-page>
         <app-admin-page>admin</app-admin-page>
      </app-root>

这将显示两个组件,一个在另一个之上。

使用路由:

      <app-root>
          <router-outlet></router-outlet>
      </app-root>

这将在此位置一次显示一个组件。使用路由配置来定义要在路由器插座中显示的组件。

RouterModule.forRoot([
  { path: 'home', component: HomeComponent },
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'admin', component: AdminComponent }
]),

我遇到了同样的问题,在某些情况下,当我点击浏览器中的“后退”按钮时,它会将当前组件与为更新的 URL 哈希定义的组件组合在一起。我能够通过在每个组件的构造函数中添加它来解决它:

      constructor(private ngZone: NgZone, private router: Router, private location: PlatformLocation, private network: NetworkService) {
    location.onPopState(() => {
      this.ngZone.run(() => this.router.navigateByUrl(location.hash.replace('#/', ''))).then();
    });
  }

然后它正确导航到前面的组件,而无需在页面上合并这两个组件。