我想用canDeactivate中的Alertify确认替换经典确认。我尝试实现以下代码,但是单击“确定”时它不会返回True。有人可以建议吗?
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { SignupComponent } from 'src/app/signup/signup.component';
import { AlertifyService } from 'src/app/_helpers/alertify.service';
@Injectable()
export class SignUpPUS implements CanDeactivate <SignupComponent> {
constructor(private alertifyService: AlertifyService) {}
canDeactivate(component: SignupComponent) {
if (component.signUpForm.dirty) {
this.alertifyService.confirm('Leave Page', 'Are you sure you want to continue? Any unsaved changes will be lost', () => {
return true;
});
}
return false;
}
}
答案 0 :(得分:1)
confirm
执行异步操作时,您需要使用Observable
,Promise
或async/await
之类的异步解决方案。
您可以按以下方式使用Observable
:
canDeactivate(component: SignupComponent) {
return new Observable((observer) => {
if (component.signUpForm.dirty) {
this.alertifyService.confirm('Leave Page', 'Are you sure you want to continue? Any unsaved changes will be lost',
() => {
observer.next(true);
},
() => {
observer.next(false);
}
);
}else{
observer.next(false);
}
observer.complete();
});
}
编辑注意:请注意,我为confirm
添加了第二个回调,以确保当用户取消确认时返回false。
答案 1 :(得分:0)
我必须进行一些细微的更改才能使其正常工作...但是接近@Harun Yimaz的答案。
AlertifyService.ts
import * as alertify from 'alertifyjs';
confirmCancel(
message: string,
okCallback: () => any,
cancelCallback: () => any
) {
alertify.confirm(message, okCallback, cancelCallback);
}
guard.ts
constructor(private alertify: AlertifyService) {}
canDeactivate(component: MemberEditComponent) {
return new Observable<boolean>(observer => {
if (component.editForm.dirty) {
this.alertify.confirmCancel(
'Are you sure you want to continue? Any unsaved changes will be lost',
() => {
observer.next(true);
observer.complete();
},
() => {
observer.next(false);
observer.complete();
}
);
} else {
observer.next(true);
observer.complete();
}
});
必须在下一个之后调用observer.complete(),以确保可观察性正确完成。