Angular 页面刷新

Oluwafisayo Oluwatayo 2023年1月30日
  1. 安装和导入一些依赖
  2. 在 Angular 中创建一个按钮以刷新页面
Angular 页面刷新

作为单页应用程序,Angular 要求在传递新数据时默认刷新应用程序。我们将研究在 Angular 上进行页面刷新的最佳方法。

安装和导入一些依赖

首先,我们必须前往我们的编辑器,最好打开终端 Visual Studio Code 并使用 ng generate 函数创建 app-routing.module.ts

然后,我们运行 $ ng generate component home 命令,之后我们运行 $ ng generate component about 命令。

创建 app-routing.module.ts 文件后,我们打开它的文件并导入以下组件。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
Next, add the routes as follows:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent }

];

这会创建两个具有不同 URL 的页面,这样如果你前往 /home 路径,它会将你带到 home 组件; about 组件也是如此。

虽然仍在 app-routing.ts 页面中,但我们在以下命令中编写代码:

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

在 Angular 中创建一个按钮以刷新页面

然后我们前往 app.component.html 创建一个按钮:

<div style="text-align:center">
    <h1>
        Welcome to {{ title }}!
    </h1>
    <a routerLink="/test" >Test</a>
    <button type="button" (click)="refresh()" >
        Refresh
    </button>
</div>

<router-outlet></router-outlet>

我们的最后一站将在 app.component.ts 部分,我们将在其中传递下一段代码。但首先,我们必须导入一些函数:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

然后我们在 app.component.ts 中运行这些代码:

@Component({
	selector: 'app-root',
	templateUrl: './app.component.html',
	styleUrls: ['./app.component.css']
})
export class AppComponent {
	title = 'refreshPage';
	constructor(public _router: Router, public _location: Location) { }
	refresh(): void {
		this._router.navigateByUrl("/refresh", { skipLocationChange: true }).then(() => {
		console.log(decodeURI(this._location.path()));
		this._router.navigate([decodeURI(this._location.path())]);
		});
	}
}

真正的魔法发生在 skipLocationChange 函数中。当点击刷新按钮时,数据在页面上传递而不刷新整个页面,这样它甚至不会记录在浏览器的历史记录中。

Oluwafisayo Oluwatayo avatar Oluwafisayo Oluwatayo avatar

Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.

LinkedIn