问题描述
我想警告用户未保存的更改,然后再离开我的angular 2应用程序的特定页面.通常我会使用window.onbeforeunload
,但这不适用于单页应用程序.
I would like to warn users of unsaved changes before they leave a particular page of my angular 2 app. Normally I would use window.onbeforeunload
, but that doesn't work for single page applications.
我发现在angular 1中,您可以挂钩到$locationChangeStart
事件为用户抛出一个confirm
框,但是我还没有看到任何显示如何使此功能适用于angular 2的东西. ,或者该事件是否仍然存在.我还看到了ag1的插件为onbeforeunload
提供了功能,但是同样,我没有看到任何方法将其用于ag2.
I've found that in angular 1, you can hook into the $locationChangeStart
event to throw up a confirm
box for the user, but I haven't seen anything that shows how to get this working for angular 2, or if that event is even still present. I've also seen plugins for ag1 that provide functionality for onbeforeunload
, but again, I haven't seen any way to use it for ag2.
我希望其他人找到了解决该问题的方法;两种方法都可以很好地达到我的目的.
I'm hoping someone else has found a solution to this problem; either method will work fine for my purposes.
推荐答案
路由器提供生命周期回调 CanDeactivate
The router provides a lifecycle callback CanDeactivate
有关更多详细信息,请参见后卫教程
for more details see the guards tutorial
class UserToken {}
class Permissions {
canActivate(user: UserToken, id: string): boolean {
return true;
}
}
@Injectable()
class CanActivateTeam implements CanActivate {
constructor(private permissions: Permissions, private currentUser: UserToken) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
return this.permissions.canActivate(this.currentUser, route.params.id);
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamCmp,
canActivate: [CanActivateTeam]
}
])
],
providers: [CanActivateTeam, UserToken, Permissions]
})
class AppModule {}
原始(RC.x路由器)
class CanActivateTeam implements CanActivate {
constructor(private permissions: Permissions, private currentUser: UserToken) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
return this.permissions.canActivate(this.currentUser, this.route.params.id);
}
}
bootstrap(AppComponent, [
CanActivateTeam,
provideRouter([{
path: 'team/:id',
component: Team,
canActivate: [CanActivateTeam]
}])
);
这篇关于在离开页面之前警告用户未保存的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!