首页 > 解决方案 > canActivate 和 canDeactivate 不能一起工作

问题描述

(角度 6)我的问题:

如何跳过第二次确认?

export interface PendingChangesComponent {
canDeactivate: () => boolean | Observable<boolean>;
}

@Injectable()
export class PendingChangesGuard implements 
CanDeactivate<PendingChangesComponent>, OnInit, OnChanges {

constructor(private confirmationservice: ConfirmationService,
    private translate: TranslateService) {
    console.log('construtor d');
}

ngOnInit() {
    console.log('init d');
}

ngOnChanges() {
    console.log('on changes d');
}

canDeactivate(component: PendingChangesComponent): boolean | Observable<boolean> {
    debugger

    if (component.canDeactivate()) {
        return true;
    }
    return Observable.create((observer: Observer<boolean>) => {
        this.confirmationservice.confirm({
            message: this.translate.instant('can.deactivate'),
            accept: () => {
                observer.next(true);
                observer.complete();
            },
            reject: () => {
                observer.next(false);
                observer.complete();
            }
        });
    });
}
}

标签: angularangular6

解决方案


当您需要导航到 C 时,您应该返回 true canDeactivate() component method...您可以设置特定的组件字段并将其设置为 true,如下所示:

// everything inside the A component


canDeactivate():boolean {
   return this.allowRedirect || yourOtherConditions;
}

// ... right before you need to navigate to C
this.allowRedirect = true;
this.router.navigate(["routeC"]);

推荐阅读