Angular - 我无法获得canDeactivate使用我的模态进行路由

时间:2018-02-06 16:48:52

标签: angular angular-routing angular-router angular-router-guards angular-route-guards

情境:

Tech:使用typescript和webpack的Angular版本5 app。

我已经做了一个 canDeactivate guard 来查看用户是否想要离开当前路线。

当用户尝试导航到另一条路线时,需要显示我已显示的自定义模式。

然后用户在模态中单击是(例如,我想离开)。

问题:

我的警卫服务受到了很好的打击,但模式方法“canDeactivate”没有被击中。因此模态不会打开。

我已将自定义模态组件添加到html。

我已将警卫和模态添加到app模块中。

这些是我的文件

DeactivateGuardService:

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 ],
  },

0 个答案:

没有答案