设想:
技术:使用 typescript 和 webpack 的 Angular 版本 5 应用程序。
我做了一个canDeactivate 守卫来查看用户是否想离开当前路线。
当用户尝试导航到另一条路线时,需要出现我展示的自定义模式。
然后用户在模式中单击“是”(例如,我想离开)。
问题:
我的警卫服务很好,但模式方法“canDeactivate”没有受到打击。因此模态不会打开。
我已将自定义模式组件添加到 html。
我已经将警卫和模态添加到应用程序模块中。
这些是我下面的文件
停用GuardService:
import { ActivatedRouteSnapshot, CanDeactivate, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { DeactivateModalComponent } from '../shared/modals/deactivate-modal/deactivate-modal.component';
@Injectable()
export class DeactivateGuardService implements CanDeactivate<DeactivateModalComponent> {
canDeactivate(component: DeactivateModalComponent) {
console.log('DeactivateGuardService');
// Note: I need this canDeactivate to call it inside my modal.
let canUse = component.canDeactivate();
return canUse;
}
}
我的自定义模式:
import { Component, EventEmitter, Output, Input, HostListener } from '@angular/core';
@Component({
selector: 'deactivate-modal',
templateUrl: 'deactivate-modal.component.html',
styleUrls: [
'../../../managed-app/managed-app.component.scss',
'../../../managed-app/shared/app-flow-styles.scss',
'deactivate-modal.component.scss',
]
})
export class DeactivateModalComponent {
public isModalVisible: boolean = false;
public isRouteActive: boolean = false;
constructor() {}
// Note: this is not getting hit - when I need it too.
canDeactivate() {
this.isModalVisible = true;
return this.isRouteActive;
}
public toggleModal(isVisible: boolean): void {
this.isModalVisible = isVisible;
}
public redirectUser(): void {
this.isRouteActive = true;
}
设置了 canDeactivate 的路由:
{
path: 'createJob',
component: testComponent,
canDeactivate: [ DeactivateGuardService ],
},