angular - canActivate 和 canDeactivate 不能一起工作
问题描述
(角度 6)我的问题:
- Route A有 canDeactivate,当我尝试去 Route B时我需要确认。
- Route B有 canActivate,我无权访问。
- 然后重定向到路由C,但此时路由A 的canDeactivate再次要求确认。
如何跳过第二次确认?
export interface PendingChangesComponent {
canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingChangesGuard implements
CanDeactivate<PendingChangesComponent>, OnInit, OnChanges {
constructor(private confirmationservice: ConfirmationService,
private translate: TranslateService) {
console.log('construtor d');
}
ngOnInit() {
console.log('init d');
}
ngOnChanges() {
console.log('on changes d');
}
canDeactivate(component: PendingChangesComponent): boolean | Observable<boolean> {
debugger
if (component.canDeactivate()) {
return true;
}
return Observable.create((observer: Observer<boolean>) => {
this.confirmationservice.confirm({
message: this.translate.instant('can.deactivate'),
accept: () => {
observer.next(true);
observer.complete();
},
reject: () => {
observer.next(false);
observer.complete();
}
});
});
}
}
解决方案
当您需要导航到 C 时,您应该返回 true canDeactivate() component method
...您可以设置特定的组件字段并将其设置为 true,如下所示:
// everything inside the A component
canDeactivate():boolean {
return this.allowRedirect || yourOtherConditions;
}
// ... right before you need to navigate to C
this.allowRedirect = true;
this.router.navigate(["routeC"]);
推荐阅读
- typescript - TypeScript 编译器 API 的“模块解析缓存”应该如何使用?
- java - 如何使用 javax.sound.sampled.LineListener?
- java - 如何在 onCreateView 中使用毕加索?
- javascript - jQuery:如果声音按钮关闭,则静音所有声音
- python - 每当我使用 conda 在 VS 代码中运行 python 脚本时,“conda activate base”
- python - asfreq 使用 Period dtype 产生意想不到的结果
- javascript - 未捕获的 SyntaxError:JavaScript 中的意外标识符 - 测验
- spring-boot - OpenAPI vs 招摇
- php - 按逗号分隔的列表排序,不带引号
- c# - 使用 For 循环更改组合框值