我想在canDeactivate中用Alertify确认替换经典的确认。我试图实现以下代码,但当单击OK时,它没有返回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;
}}
发布于 2019-03-18 15:32:12
在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。
发布于 2020-02-24 22:03:14
我不得不做一些细微的改变来让它工作起来...但是接近@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();
}
});必须在next之后调用observer.complete(),以便observable正确完成。
https://stackoverflow.com/questions/55214245
复制相似问题