在需要进行路由守卫时,可以在路由配置文件中使用以下代码:
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';
export interface ComponentCanDeactivate {
canDeactivate: () => Observable | Promise | boolean;
}
@Injectable()
export class PendingChangesGuard implements CanDeactivate {
canDeactivate(component: ComponentCanDeactivate): Observable | Promise | boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
这将导出一个名为ComponentCanDeactivate
的接口,它可以提供canDeactivate
方法,并让路由守卫了解该组件中是否有该方法。通过该方法,我们可以在用户即将离开该组件或页面时通过返回一个布尔值或一个 Promise,来提供一个提示信息。例如,以下是一个示例组件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.scss']
})
export class YourComponentComponent implements ComponentCanDeactivate, OnInit {
formChanged = false;
constructor() {}
ngOnInit() {}
canDeactivate(): Observable | Promise | boolean {
if (this.formChanged) {
return confirm('You have unsaved changes. Are you sure you want to discard them?');
}
return true;
}
}
如果用户在该组件中进行了更改,则该组件的formChanged
属性将标记为 true。当用户即将离开该组件或页面时,我们将检查formChanged
属性,如果已更改则弹出提示框来获取用户的意见。当用户单击 "是" 时,将返回 true,而如果用户点击 "否" 或 "取消" 按钮时,则返回 false,从而防止用户离开该组件页面。 确认方法返回了一个布尔值,表示用户是否