【问题标题】:Angular routing, is the entire html page reloaded, or just a portion of the page?角度路由,是重新加载整个 html 页面,还是只是页面的一部分?
【发布时间】:2020-05-16 17:37:03
【问题描述】:

我想找到答案:在 Angular 路由中,当单击链接并生成路由 url 时,是重新加载整个 html 页面,还是仅重新加载页面的一部分?

使用 Angular 基础教程“Tour of Heroes”,我在每个组件的 html 模板中添加了一条语句,以不同颜色绘制一个框(代码来自here 和此处)。比如……

<h1>{{title}}</h1>
<nav>
  <a routerLink="/dashboard">Dashboard</a>
  <a routerLink="/heroes">Heroes</a>
</nav>
<div style="width:100px;height:100px;border:1px solid rgb(255, 255, 0);">This is app component!</div>

<router-outlet></router-outlet>
<app-messages></app-messages> 

但我无法判断是否只重绘了面板而不是整个页面。

为了测试这一点,我想每次都用随机颜色绘制矩形。 创建随机颜色形状的目的是区分矩形是改变颜色(整个页面被重新加载)还是组件中只有矩形的颜色改变(然后只有组件被重新加载)。

关注herehere的文章

我创建了一个 src/custom.js 文件并将其放入

(function random_rgba() {
    var o = Math.round, r = Math.random, s = 255;
   // return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
    document.write("<div style=\"width:100px;height:100px;border:1px solid " + " rgb(0, 255, 0);" + ">This is a hero detail component!</div>");
})()

在 angular.json 中,

    "scripts": [
      "src/custom.js"
    ]

但是在 hero-detail.component.html 中

<div><script>random_rgba();</script></div>

重新加载页面时没有绘制彩色矩形。 :(

【问题讨论】:

  • 你查看浏览器开发者工具的网络标签了吗?
  • @DiogoSantana 感谢您的提示。我刚才看了。没有活动,但那是因为本教程没有进行任何网络调用。

标签: html angular


【解决方案1】:

您使用的“routerLink”属性是 Angular 路由器的一部分。 Angular 路由器负责更改 URL 并相应地显示组件。当您使用它时,它不会刷新整个浏览器。

只有在你的路由数组中匹配的组件才会被重新加载。 Router Outlet 上方/外部的所有组件都保持其本地状态,并且不会被路由重建。

你也可以有多个Router Outlets,如果是这样,只有相关Router Outlet里面的部分会被重新加载。

如果您从变更检测的角度来看它,那么变更检测很可能会在您的整个应用程序中运行,因为它会在所有其他发生的事件上运行。不过,可以通过在组件中使用更改检测策略 OnPush 来避免这种情况。

【讨论】:

  • 不清楚const routes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: DashboardComponent }, { path: 'detail/:id', component: HeroDetailComponent }, { path: 'heroes', component: HeroesComponent } ];如果用户点击一个id,那么这个Routes数组中的所有组件是否会重新加载?或者只有HeroDetailComponent
  • @likejudo 只有 HeroDetailComponent 会重新加载。我会尝试改写一下我的答案。
  • 我正在尝试测试您写的内容并更新了我的问题,但是我的 JS 中存在一些错误,因为没有绘制彩色矩形 :(
  • 我认为您不能在 Angular 的 html 模板中放置
  • 但是创建随机颜色形状的目的是区分矩形是否改变颜色(重新加载整个页面)或是否只有组件中矩形的颜色发生变化(然后仅重新加载组件)。跨度>
猜你喜欢
  • 2018-03-13
  • 2020-12-03
  • 2017-11-26
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
相关资源
最近更新 更多