在Angular 7中,你可以使用CanDeactivate
守卫来限制导航以防止浏览器挂起。下面是一个包含代码示例的解决方法:
首先,创建一个名为can-deactivate.guard.ts
的文件,并将以下代码添加到文件中:
import { Injectable } from '@angular/core';
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
export interface CanComponentDeactivate {
canDeactivate: () => Observable | Promise | boolean;
}
@Injectable({
providedIn: 'root'
})
export class CanDeactivateGuard implements CanDeactivate {
canDeactivate(
component: CanComponentDeactivate,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot
): Observable | Promise | boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
接下来,在要限制导航的组件中,实现CanComponentDeactivate
接口,并添加canDeactivate
方法。在该方法中,你可以放置任何防止导航的逻辑。下面是一个简单的示例:
import { Component } from '@angular/core';
import { CanComponentDeactivate } from './can-deactivate.guard';
import { Observable } from 'rxjs';
@Component({
selector: 'app-my-component',
template: `
My Component
`
})
export class MyComponent implements CanComponentDeactivate {
canDeactivate(): Observable | Promise | boolean {
return confirm('Are you sure you want to navigate away?');
}
navigateAway() {
// 导航到其他路由
}
}
最后,在路由模块中注册CanDeactivateGuard
守卫。找到你的路由模块文件(通常是app-routing.module.ts
),并在Routes
数组中添加以下代码:
import { CanDeactivateGuard } from './can-deactivate.guard';
import { MyComponent } from './my-component';
const routes: Routes = [
{
path: 'my-component',
component: MyComponent,
canDeactivate: [CanDeactivateGuard]
}
];
现在,当用户尝试导航离开MyComponent
时,将触发canDeactivate
方法。如果该方法返回false
,导航将被阻止。你可以根据需要在canDeactivate
方法中放置自定义逻辑。