如何解决angular 9,我可以使用canDeactivate路由到其他地方吗?
感谢您在这里花时间。
因此我对canDeactivate没什么问题。 我做了一个页面,如果我单击“返回”按钮,则会出现一个模态显示, 用户可以选择是否转义该页面。 如果我只单击一次,那很好。 但这是问题所在。 假设我位于[页面A->页面B-> C页面] 在C页上,我放置canDeactivate。 因此,如果当我单击“返回”时在“模态”上单击“确定”,它将很好地移动到B页。 但是,如果我先单击“模态”上的“取消”,然后再次单击“返回”,则当我单击“确定”时,它将移至页面A。 当然,每当我调用canDeactivate时,无论我单击什么模态,它的行为都像它已经移动了。
所以我想做的就是不管我叫多少次canDeactivate,当我在模式对话框中单击“确定”时,我想移至页面B。 希望你们对我都有解决办法。
canDeactivate.file
export class DeactiveGuard implements CanDeactivate<Grammarcomponent> {
constructor(private router: Router) {}
canDeactivate(component: Grammarcomponent) {
return component.canDeactivate ? component.canDeactivate() : true
}
}
第C.file页
public canDeactivate() {
if (!this.exceptCanDeactivate) {
return from(
this.modalService.open(this.exitFromExamMd,{
centered: true,scrollable: true,windowClass: 'final-confirm',}).result,).pipe(map((result) => result === 'yes'))
} else {
return true
}
}
解决方法
根据Angular docs,canDeactivate
卫队可以返回UrlTree
,Observable<UrlTree>
甚至是Promise<UrlTree>
等。 UrlTree
是一种导航到所需位置的方法。在指定命运时,无论单击何处消失,都将始终重定向到相同的命运。
这就是您可以做的:在您的守护程序中,返回一个可观察到的内容,该内容在您关闭对话框时会在内部发出(在此示例中,我假设使用异步确认对话框API,就像我们在@ angular / material对话框中一样) ):
@Injectable({providedIn: 'root'})
export class CanDeactivateGuard implements CanDeactivate<YourComponent> {
constructor(private matDialog: MatDialog,private router: Router) {}
canDeactivate(
component: YourComponent,route: ActivatedRouteSnapshot,state: RouterStateSnapshot
): Observable<UrlTree> {
const observable = new Observable(observer => {
const dialogRef = this.matDialog.open(YourConfirmationDialogComponent);
dialogRef.afterClosed().subscribe((okButtonClicked) => {
observer.next(this.router.parseUrl(urlString));
observer.complete();
});
});
return observable;
}
}
在您的情况下,因为您使用的是NgbModal:
constructor(private modalService: ModalManager) {}
canDeactivate(): Observable<UrlTree> {
const observable = new Observable(observer => {
const dialogRef = this.modalService.open(this.exitFromExamMd,{
centered: true,scrollable: true,windowClass: 'final-confirm',});
dialogRef.onClose.subscribe(() => {
observer.next(this.router.parseUrl(urlString));
observer.complete();
});
});
return observable;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。