Angular 8 中的 Router Guards

Router Guards in Angular 8

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

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

1。为 CanDeactivate Guard 创建服务

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

deactivate.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;

  }
}

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

2。在应用程序路由模块中配置 CanDeactivate Guard 服务

app.module.ts:

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

------
@NgModule({
  ------
  providers: [ 
    CanDeactivateGuard
  ]
})
export class AppRoutingModule { } 

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

formComponent.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;
}

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

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

应用-routing.module.ts:

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

  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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