我刚刚开始将一个应用迁移到Angular + Flex-Layout + Angular Material。
我决定将我的路由放在一个名为"app-routing.module.ts“的外部文件中。我在"imports“中的app.module.ts中导出我的模块。这是我的路由文件:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component'
import { CreateMatchComponent } from './match/create-match.component'
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'match/new', component: CreateMatchComponent}
];
@NgModule({
imports: [ RouterModule.forRoot(routes)],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
下面是呈现我的路由器插座的app.component的超文本标记语言。
<div class="containerX">
<div fxLayout="row wrap">
<mat-toolbar color="primary" class="mat-elevation-z4">
<span>Amazing Football Stats App</span>
<span class="example-spacer"></span>
<mat-icon class="example-icon">favorite</mat-icon>
<mat-icon class="example-icon">delete</mat-icon>
</mat-toolbar>
</div>
<div fxLayout="row wrap" style="padding-top: 8px">
<router-outlet></router-outlet>
</div>
</div>
如您所见,我的应用程序组件有一个带有导航栏的div,然后还有一个带有<router-outlet>
的div。
如果我转到localhost:4200
,它会加载包含<nav-bar>
和<router-outlet>
的<app-root>
,因为“<nav-bar>
”是空的,所以它会将我重定向到"/home“。
现在我的问题是:如果我将URL更改为:localhost:4200/match/new
(在浏览器中,在地址栏中)按enter,我可能会离开<nav-bar>
,只更新<router-outlet>
,同样的操作会向后进行。
如果我在不同的页面上,并且我将URL更改为"/home“(甚至将其保留为空),它应该保留导航栏,而只更新路由器插座。
如果这是一个愚蠢的问题,我很抱歉,我刚从angular routing开始。我做错了什么?
发布于 2017-10-11 04:52:22
当您更改浏览器位置时,浏览器将处理该更改,并将向您的服务器发送新的HTTP请求。这就是它重新加载整个页面的原因。
为了只更改加载到<router-outlet>
中的组件,您需要Angular的路由器来处理更改,这是通过使用routerLink指令完成的:
<a routerLink="match/new" routerLinkActive="active">Create Match</a>
或以编程方式调用router.navigate
constructor(private router: Router) {}
...
goToCreateMatch() {
this.router.navigate(['/match/new']);
}
这里有一个指向angular文档的链接,了解更多信息:
https://stackoverflow.com/questions/46675661
复制相似问题