簡體   English   中英

為什么 Angular 兩次加載我的根模板

[英]Why is Angular loading my root template twice

即使我的主頁有一個單獨的組件,我的根組件也會加載兩次。 我嘗試使用不同的東西,例如pathMatch 、單獨的組件等,但沒有運氣。 當我轉到/dashboard時,它工作得很好,但是當它最初加載頁面(根頁面)時,導航欄被加載了兩次。 我想避免這種情況。+

我的代碼如下所示:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { NavbarComponent } from './navbar/navbar.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { RouterModule, Routes } from '@angular/router';
import { RootComponent } from './root/root.component';
import { FeatureDashboardComponent } from '@angular/dashboard';
import { FeatureHomepageComponent } from '@angular/homepage';

const routes: Routes = [
  {
    path: '',
    component: RootComponent,
    pathMatch: 'full',
    children: [
      { 
        path: '',
        component: FeatureHomepageComponent
      }
    ]
  },
  {
    path: 'dashboard',
    component: FeatureDashboardComponent
  },
  {
    path: '**',
    redirectTo: ''
  }
];

@NgModule({
  declarations: [
    NavbarComponent,
    RootComponent
  ],
  imports: [
    BrowserModule,
    NgbModule,
    RouterModule.forRoot(routes)],
  providers: [],
  bootstrap: [RootComponent],
})
export class AppModule {}

我的 RootComponent 的 HTML 是:

<angular-navbar></angular-navbar>
<div class="layout">
    <router-outlet></router-outlet>
</div>

導航欄是:

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container-fluid">
      <a class="navbar-brand">My App</a>
    </div> 
</nav>

檢查中的示例

我認為問題可能是您有路由''加載RootComponent並且子路由嘗試加載FeatureHomepageComponent但也是'' ,路由器無法有效解決。

嘗試給子路由一個不為空的路徑,如下所示:

...
{
    path: '',
    component: RootComponent,
    pathMatch: 'full',
    children: [
      { 
        path: 'home',
        component: FeatureHomepageComponent
      }
    ]
  },
...

並在最后使用重定向,因此當您的應用程序加載時,它應該導航到(例如) localhost:4200/home

我認為問題在於這段代碼:

path: '',
component: RootComponent,

你很可能不想讓你的 RootComponent 出現在這里,因為它會允許 RootComponent 出現在你的

<router-outlet> 

並且可以解釋為什么你有 2 個。

<router-outlet> 

應該只路由到您的 RootComponent 的 CHILDREN。

換句話說,沒有路由(在你的路由配置中)應該渲染你的 RootComponent 它已經被渲染了。 那里的路由應該只呈現你想要在你的路由器插座中顯示的內容,也就是你的 RootComponent 的 CHILDREN

對於解決方案,我認為您只需要這樣做:

path: '',
component: FeatureHomepageComponent

配置中的第一個路徑(刪除 RootComponet 部分和 children:[] 部分)

嘗試調用確切的組件名稱,而不是調用router-outlet

這意味着您有兩個之一:另一個<router-outlet></router-outlet>實例,或者您在另一個模板中實例化<angular-navbar></angular-navbar> ,而不是您在此處顯示的模板。 pathMatch與這里無關,因為<angular-navbar></angular-navbar>組件與路由無關,這意味着它是一個布局組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM