#angular #rxjs
#angular #rxjs
Вопрос:
В canDeactivate guard я подписываюсь на службу подтверждения. Компонент подтверждения имеет 3 кнопки, и при нажатии на одну из них он извлекает перечисление. Как я могу проверить значение в subscribe to view, сделать что-то и вернуть логическое значение для guard в зависимости от значения?
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();
}
Ответ №1:
canDeactivate ожидает наблюдаемого, вы можете сделать что-то вроде этого :
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
Я надеюсь, что это поможет вам!