【问题标题】:Angular's route guard is not running within appAngular 路由保护未在应用程序中运行
【发布时间】:2019-02-25 09:00:10
【问题描述】:

我在我的app-routing.module.ts 文件中添加了一条带有保护的路线,如下所示:

{path: 'detail/:id', component: DetailComponent, canDeactivate: [PendingChangesGuard]},

如果我尝试完全退出 Angular 应用程序,那么我会看到我预期的消息从 PendingChangesGuard 弹出。但是,如果我单击 Angular 应用程序中的任何其他路由,则不会执行路由保护。在这种情况下我如何让它也运行?

这是路由保护文件的样子:

export interface ComponentCanDeactivate {
    canDeactivate: () => boolean;
}

@Injectable({
    providedIn: 'root'
})
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
    canDeactivate(component: ComponentCanDeactivate, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        return component.canDeactivate ? true : confirm('WARNING: You have unsaved changes. Press Cancel to go back and save your changes.');
    }
}

DetailComponent 我这样做了:

@HostListener('window:beforeunload')
canDeactivate(): boolean {
    console.info("I got called");
    return !this.formGroup.dirty;
}

【问题讨论】:

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


    【解决方案1】:

    你实际上并没有打电话给component.canDeactivate。您基本上是在检查它是否已定义(始终为 true),然后返回 true

    更新到:

    export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
        canDeactivate(component: ComponentCanDeactivate, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
            return component.canDeactivate() ? true : confirm('WARNING: You have unsaved changes. Press Cancel to go back and save your changes.');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      相关资源
      最近更新 更多