在canDeactivate Guard中,我订阅确认服务。确认组件具有3个按钮,并且单击其中之一时,它将弹出枚举。如何在订阅视图中检查值,执行smth并根据值返回boolean值作为防护?
CanDeactivateGuard:
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
constructor(private modalDialogService: ModalService) {
}
canDeactivate(component: CanComponentDeactivate,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | boolean {
if (!component.isUnsavedChanges()) {
return true;
}
this.modalDialogService.showConfirm(ConfirmType.CAN_DEACTIVATE).subscribe(val => {
//here I want to check value, do some functions and return true/false
})
}
}
ConfirmComponent:
export class ConfirmComponent {
subject: Subject<ConfirmAction>;
constructor(public bsModalRef: BsModalRef) {}
action(action: ConfirmAction):void { //here the value of click
this.bsModalRef.hide();
this.subject.next(action);
this.subject.complete();
}
}
export enum ConfirmAction {
SAVE,
REVERT,
CANCEl,
}
ModalService:
export class ModalService {
constructor(private bsModalService: BsModalService,
private ts: TranslatorService) {}
public showConfirm(modalDialogType: ConfirmType, extraInfo?: string): Observable<ConfirmAction> {
let modal;
switch (modalDialogType) {
case ConfirmType.CAN_DEACTIVATE: {
modal = this.bsModalService.show(ConfirmComponent, config);
break;
}
/*
other cases
*/
return modal.content.subject.asObservable();
}
答案 0 :(得分:0)
canDeactivate正在等待Observable,您可以执行以下操作:
canDeactivate(component: CanComponentDeactivate,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | boolean {
if (!component.isUnsavedChanges()) {
return true;
}
return this.modalDialogService.showConfirm(ConfirmType.CAN_DEACTIVATE).pipe(
map(val => {
// Here, do your work and return true or false
})
)
}
看看Rxjs文档https://rxjs-dev.firebaseapp.com/guide/overview
我希望它能对您有所帮助!