canActivate和canDeactivate不能一起使用

时间:2019-01-23 17:13:56

标签: angular angular6

(角度6)我的问题:

  • 路线 A 具有canDeactivate,当我尝试转到路线 B 时,我需要确认。
  • 路线 B 具有canActivate,我无权访问。
  • 然后重定向到Route C ,但此时可以从Route A 停用以再次请求确认。

如何跳过第二次确认?

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();
            }
        });
    });
}
}

1 个答案:

答案 0 :(得分:0)

当您需要导航到C时,应在canDeactivate() component method中返回true。您可以设置特定的组件字段并将其设置为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"]);