如何在Angular中重新加载一个页面/组件?

1,959 阅读3分钟

本教程讨论了在angular框架中实现重载/刷新的两种方法。一种是使用window.reload来重新加载整个页面,另一种是使用onSameUrlNavigation-reload刷新组件与角度路由器。

有些时候,作为一个开发者,你需要写一个逻辑来重新加载一个组件或一个页面,如下情况

  • 在点击按钮时刷新一个组件
  • 在删除时重新加载一个组件的数据

在Angular中,页面导航可以通过或不通过Angular路由器模块来完成。

让我们讨论一下如何在Angular中以多种方式重新加载或刷新组件。

在Angular中,页面也可以用windows.location reload来重新加载。

以下是一个通过点击按钮重新加载页面的例子

在Angular html组件--app.component.html中

在模板中添加按钮和按钮点击事件处理器,你可以查看如何在Angular中添加按钮点击


 <div >
    <p>
       Angular Button Click Event Example
    </p>
    <button  (click)="reloadCurrentPage()" >
    Reload Page</button>
    <h2>{{msg}}</h2>
 </div>
 

在typecript组件中 - app.component.ts

  • 写一个函数 - reloadCurrentPage
  • 因为window是一个全局对象,可以直接在Angular组件中重复使用。
  • window.location.reload() 加载当前页面
 reloadCurrentPage() {
    window.location.reload();
   }

在一个传统的Web应用程序中,从一个页面移动到另一个页面会重新加载页面和它的内容。另一方面,页面刷新会重新加载整个页面。Window.location.reload可以用来实现这个目的。这与用户刷新他们的浏览器是一样的。

在单页应用程序中,我们用多个组件包装了一个单页,当用户导航到另一个页面时,它只加载该页面需要的组件。当用户执行一个操作时,比如点击一个按钮,只加载那个组件,而不是加载页面上的所有组件。

window...reload并不是像Angular这样的单页应用中建议的重新加载整个页面的方法,所以这种方法对于单页应用并不理想。

让我们来看看我们如何使用Angular路由器模块来重新加载组件。

用Angular router重新加载组件

首先,我们将用ng cli命令安装angular router模块,然后我们将配置router模块的变化,这将不作为这篇文章的一部分。

在app-routing.module.ts文件中,需要配置的是

onSameUrlNavigation:reload 属性必须被添加到app-routing.module.ts文件中。这些文件提供了关于如何配置全局路由变化的路由器配置。

import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { DashboardComponent }from './dashboard/dashboard.component';
import {ProfileComponent} from './profile/profile.component';

@NgModule({
  declarations: [ 
  ],
  imports: [
    RouterModule.forRoot([
      {path: 'dashboard', component:DashboardComponent}
    ],{ onSameUrlNavigation: 'reload' })
  ],
  exports: [
    RouterModule,
  ],
  providers: [],
})
export class AppRoutingModule {}

在html模板中,

仪表板组件已被定义为

  • 在输入表单中添加了一个带有点击事件处理程序的按钮
  • 当按钮被点击时,事件处理程序被调用,并且这个组件被重新加载。

<p>
<button (click)= "refreshComponent()"> Refresh Dashboard component </button>
</p>

输入类型脚本组件

已经定义了Dashboard组件的typecript

  • 在构造函数中注入路由器对象
  • 定义函数,并使用this.router.url重新加载当前组件。
import { Component } from '@angular/core';
import {Router, NavigationEnd,ActivatedRoute} from '@angular/router';
@Component({
  selector: 'my-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent {
    constructor(private router: Router, private activatedRoute: ActivatedRoute) {
  }
  ngOnInit() {
  }

  refreshComponent(){
     this.router.navigate([this.router.url])
  }

}

在Angular中,这就是我们如何通过路由器的变化来重新加载一个组件。

总结

本文讨论了两种方法:第一种是使用window.location.reload在浏览器上重新加载整个页面,第二种是使用angular router模块来重新加载页面中的组件。