在Angular中,可以使用CanDeactivate守卫来阻止路由的进一步导航。以下是一个示例代码:
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable()
export class PreventNavigationGuard implements CanDeactivate {
canDeactivate(): Observable | Promise | boolean {
// 在这里添加你的逻辑来判断是否允许导航
// 返回true表示允许导航,返回false表示阻止导航
return confirm('确定要离开吗?');
}
}
import { PreventNavigationGuard } from './prevent-navigation.guard';
const routes: Routes = [
{
path: 'example',
component: ExampleComponent,
canDeactivate: [PreventNavigationGuard]
}
];
import { Component } from '@angular/core';
import { CanComponentDeactivate } from './can-component-deactivate';
@Component({
selector: 'app-example',
template: `
`
})
export class ExampleComponent implements CanComponentDeactivate {
canDeactivate(): Observable | Promise | boolean {
// 在这里添加你的逻辑来判断是否允许导航
// 返回true表示允许导航,返回false表示阻止导航
return confirm('确定要离开吗?');
}
}
这样,在用户尝试离开该路由时,会触发CanDeactivate守卫中的canDeactivate方法来判断是否允许导航。如果返回true,则允许导航;如果返回false,则阻止导航。