Angular 5中检测浏览器刷新及失败页防回退刷新需求实现
Hey there! Let's walk through how to implement your Angular 5 requirements step by step—covering form submission validation, locking the failure page to prevent back navigation, keeping users on the failure page after refresh, and detecting browser refresh actions.
First, handle the form submit action, call your validation service, and navigate to the appropriate page based on the response. Here's a sample component implementation:
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { ValidationService } from './validation.service'; @Component({ selector: 'app-input-form', templateUrl: './input-form.component.html' }) export class InputFormComponent { userInput: string; constructor(private router: Router, private validationService: ValidationService) {} onSubmit() { // Call your validation service this.validationService.validateInput(this.userInput).subscribe( (isValid) => { if (isValid) { // Navigate to success page if input is valid this.router.navigate(['/success']); } else { // Navigate to failure page, and set up state for locking this.router.navigate(['/failure']).then(() => { // Replace current history entry to block back button navigation window.history.replaceState({}, document.title, window.location.href); // Store failure page state in sessionStorage to persist through refresh sessionStorage.setItem('isOnFailurePage', 'true'); }); } }, (error) => { // Treat service errors as invalid input, navigate to failure page this.router.navigate(['/failure']).then(() => { window.history.replaceState({}, document.title, window.location.href); sessionStorage.setItem('isOnFailurePage', 'true'); }); } ); } }
You need two key behaviors here: preventing users from navigating back, and keeping them on the failure page after a refresh.
Prevent Back Navigation
Create a route guard to block navigation away from the failure page (except when the browser is closed):
import { CanDeactivate } from '@angular/router'; import { FailureComponent } from './failure/failure.component'; export class PreventLeaveFailurePageGuard implements CanDeactivate<FailureComponent> { canDeactivate(): boolean { // Return false to block navigation away from the failure page return false; } }
Register this guard in your routing module:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { FailureComponent } from './failure/failure.component'; import { PreventLeaveFailurePageGuard } from './prevent-leave-failure.guard'; const routes: Routes = [ // ... your other routes { path: 'failure', component: FailureComponent, canDeactivate: [PreventLeaveFailurePageGuard] } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [PreventLeaveFailurePageGuard] }) export class AppRoutingModule { }
Persist Failure Page on Refresh
Add logic to your AppComponent to check for the failure page state on app initialization, and redirect back to the failure page if needed:
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit { constructor(private router: Router) {} ngOnInit() { const isOnFailurePage = sessionStorage.getItem('isOnFailurePage'); if (isOnFailurePage === 'true') { this.router.navigate(['/failure']); } } }
Update your FailureComponent to maintain the session storage flag and inform users of their options:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-failure', templateUrl: './failure.component.html' }) export class FailureComponent implements OnInit { ngOnInit() { // Ensure the flag is set when the component loads sessionStorage.setItem('isOnFailurePage', 'true'); } }
Sample template for failure.component.html:
<div class="failure-page"> <h2>Input Invalid/Illegal</h2> <p>Your submission could not be processed. You can only close the browser to exit this page.</p> </div>
Use Angular's HostListener to listen for the beforeunload event, which triggers when the page is about to refresh, close, or navigate away:
import { Component, HostListener } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { @HostListener('window:beforeunload', ['$event']) handleBeforeUnload(event: Event) { // This triggers on F5, right-click reload, or browser close console.log('Page is about to refresh or close'); // Optional: Show a confirmation dialog (note: browsers may restrict custom messages) // event.returnValue = 'Are you sure you want to leave this page?'; } }
This lets you detect refresh actions, and combined with the session storage flag, ensures users stay on the failure page after refreshing.
内容的提问来源于stack exchange,提问作者juniorDeveloper

