Angular 8 中的路由器防护

Sha*_*ank 0 angular angular-router-guards candeactivate

我创建了一个用户输入数据的应用程序。在该应用程序上,我想实现路由器防护来拒绝用户返回页面,这样他们就不会丢失数据。如果用户单击浏览器上的后退按钮,它会重新加载页面而不是返回?

我正在考虑使用 canDeactivate 拒绝访问上一页,并使用 Angular Location 来确定用户所在的页面,然后重新加载该页面。但我不知道如何实现这一点。

Raf*_*nig 5

1. 为 CanDeactivate Guard 创建服务

首先,您必须创建一个将声明canDeactivate方法的接口,并使用此接口您将创建一个充当守卫的服务canDeactivate。该服务将定义canDeactivate方法如下:

停用.guard.ts:

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';

export interface CanComponentDeactivate {
  canDeactivate(): boolean;
}

@Injectable()
export class DeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate): boolean {

    /*
    The return value would be true, unless the canActivate function, 
    defined on the component returns false,
    in which case the function will open a Dialog Box,
    to ask if we want to stay on the page or leave the page.
    */
    if (component.canDeactivate()) return true;
    else return confirm('You have unsaved changes!') ? true : false;

  }
}
Run Code Online (Sandbox Code Playgroud)

该接口已声明canDeactivate方法,其返回类型为布尔值。在服务代码中,我们canDeactivate使用组件实例调用方法。

2. 在应用路由模块中配置CanDeactivate Guard服务

应用程序模块.ts:

import { CanDeactivateGuard } from './can-deactivate-guard.service';

------
@NgModule({
  ------
  providers: [ 
    CanDeactivateGuard
  ]
})
export class AppRoutingModule { } 
Run Code Online (Sandbox Code Playgroud)

3. 在您的组件中创建 canDeactivate() 方法

表单组件.ts:

import { Component, HostListener } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { CanComponentDeactivate } from 'src/app/deactivate.guard';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements CanComponentDeactivate {
  saved: boolean;
  form: FormGroup;
  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: ['']
    });
  }

  /* Prevent page reloading */
  @HostListener('window:beforeunload', ['$event'])
  canReload(e) {
    if (!this.canDeactivate()) e.returnValue = true;
  }

  submit = () => this.saved = true;
  canDeactivate = () => this.saved || !this.form.dirty;
}
Run Code Online (Sandbox Code Playgroud)

4.在路由模块的组件路由中添加CanDeactivate Guard

您需要使用canDeactivate属性将我们的CanDeactivate守卫.ie DeactivateGuard添加到路由模块中的组件路由中。

应用程序路由.module.ts:

const routes: Routes = [
  {
    path: 'home',
    component: FormComponent,
    canDeactivate: [DeactivateGuard]
  },
  { path: 'next', component: NextComponent },

  { path: '', redirectTo: '/home', pathMatch: 'full' }
];
Run Code Online (Sandbox Code Playgroud)

您不妨考虑将数据存储在服务中,因为它可能是更好的选择。