【问题标题】:Router Guards in Angular 8Angular 8 中的路由器防护
【发布时间】:2019-11-01 19:51:13
【问题描述】:

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

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

【问题讨论】:

标签: angular angular-router-guards candeactivate


【解决方案1】:

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 方法,其返回类型为布尔值。在服务代码中,我们使用组件实例调用了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 守卫。即使用 canDeactivate 属性将路由模块中的组件路由停用。

app-routing.module.ts:

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

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

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

【讨论】:

  • 你说得对,让我看看我能做些什么
  • 我已经更新了答案,让我知道它是否适合你。
  • 我可以为多个页面执行此操作吗?
  • 让我了解你想要什么。据了解,您希望您的页面在返回导航时刷新,您希望如何保存数据?更好的方法是在有未保存的数据时防止重新加载或任何页面导航。
  • 谢谢我实际上尝试了不同的选项,但我认为最好阻止任何页面导航
猜你喜欢
  • 1970-01-01
  • 2022-09-27
  • 2017-02-12
  • 2019-07-03
  • 2020-02-25
  • 1970-01-01
  • 2018-11-30
  • 2020-05-24
  • 2020-01-15
相关资源
最近更新 更多