【问题标题】:Why don't components in same module load with router.navigate?为什么同一模块中的组件不使用 router.navigate 加载?
【发布时间】:2020-06-14 07:46:33
【问题描述】:

在有人将此问题标记为重复之前,我尝试了以下问题:

Angular 5 router.navigate does not work

router.navigate is not working (Angular6, lazy loading)

router navigate doesn't redirect to other page

我尝试了这些问题的解决方案,但没有任何效果。所以我来这里问我自己的问题。 现在问题来了:

我创建了一个新应用程序,我试图从App.Componentrouter.navigate() 路由到Home.Component。以下是供参考的文件:

应用组件.html

<p>App component works</p>
<button (click)="onClick()">Click Home</button>

App.component.ts

import { Router, ActivatedRoute } from '@angular/router';
export class AppComponent {
  constructor(private router:Router){}
  onClick(){
    console.log("Button clicked!!");
    this.router.navigate(['home']);
  }
}

app-routing.module.ts

const routes: Routes = [
  { path:'', component: AppComponent, pathMatch:'full'},
  {path:'home', component:HomeComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

我不明白为什么单击Click Home 按钮时没有加载home.component.html

另外,我尝试创建另一个组件Second.component 并尝试在按钮单击时从Home.component 加载相同的组件(Home.component 内的按钮)。

组件不是延迟加载的(它们在同一个模块中)。 每当我单击按钮时,网址都会更改。那么为什么关联的组件不加载呢?我错过了配置的某些部分吗? Here is the demo

【问题讨论】:

  • 你能为此分享stackblitz吗?
  • @silentsudo 我正在更新问题。请在其中找到 stackblitz url。

标签: angular typescript


【解决方案1】:

您在应用启动时看到的应用组件在那里是因为它是引导组件,而不是因为它在激活的路由上。您将需要有 o &lt;router-outlet&gt; 元素来呈现与当前路径匹配的组件。

根据您要实现的目标,为了不重复页面上的元素,您可能需要拆分AppComponent。一部分应该被引导并且只包含路由器出口。另一部分应该只包含按钮。

我猜您正在尝试添加一个将显示在所有页面上的菜单,以及您可以导航到的几个页面。在这种情况下,您可以(例如) 将AppComponent 保留为引导组件,并在其中添加&lt;router-outlet&gt; 和菜单:

<p>App component works</p>
<button (click)="onClick()">Home</button>
<button (click)="goToSomeOtherPage()">Some other page</button>
<router-outlet></router-outlet>

然后,编辑您的路线定义,使用户实际上看不到空路径:

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch:'full'},
  { path: 'home', component: HomeComponent },
  { path: 'some/other/page', component: SomeOtherComponent },
];

随着菜单变得越来越复杂,您可以使用 child routes 将其拆分为单独的组件(例如 MainMenuComponent)。

【讨论】:

  • 那么我是否需要为每个重定向到任何其他组件的组件添加&lt;router-outlet&gt;?我如何拆分 AppComponent,因为添加 router-outlet 确实复制了元素?
  • 在大多数情况下,您需要在整个应用程序中使用一个路由器插座。它将被放置在顶级组件之一中。它的内容将显示与当前路径匹配的任何组件。
猜你喜欢
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 2017-09-23
  • 1970-01-01
  • 2015-07-13
  • 2016-09-12
  • 2019-05-28
相关资源
最近更新 更多