首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当在angular 4中有一个外部路由文件时,为什么我的应用程序重新加载整个页面而不是组件?

当在angular 4中有一个外部路由文件时,为什么我的应用程序重新加载整个页面而不是组件?
EN

Stack Overflow用户
提问于 2017-10-11 04:43:01
回答 1查看 102关注 0票数 0

我刚刚开始将一个应用迁移到Angular + Flex-Layout + Angular Material。

我决定将我的路由放在一个名为"app-routing.module.ts“的外部文件中。我在"imports“中的app.module.ts中导出我的模块。这是我的路由文件:

代码语言:javascript
运行
复制
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的超文本标记语言。

代码语言:javascript
运行
复制
<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开始。我做错了什么?

EN

回答 1

Stack Overflow用户

发布于 2017-10-11 04:52:22

当您更改浏览器位置时,浏览器将处理该更改,并将向您的服务器发送新的HTTP请求。这就是它重新加载整个页面的原因。

为了只更改加载到<router-outlet>中的组件,您需要Angular的路由器来处理更改,这是通过使用routerLink指令完成的:

代码语言:javascript
运行
复制
<a routerLink="match/new" routerLinkActive="active">Create Match</a>

或以编程方式调用router.navigate

代码语言:javascript
运行
复制
constructor(private router: Router) {}
...
goToCreateMatch() {
    this.router.navigate(['/match/new']);
}

这里有一个指向angular文档的链接,了解更多信息:

https://angular.io/guide/router#router-links

https://angular.io/api/router/Router#navigate

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46675661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档