javascript - Angular 2 : How to apply a callback when I leave a route

标签 javascript angular angular2-routing

这是例子,我在 AppComponent 中定义了一些路由:

@RouteConfig([
  {path:'/',         name: 'Index', component: IndexComponent, useAsDefault: true},
  {path:'/:id/...',  name: 'User',  component: UserComponent},
  {path:'/plan',     name: 'Plan',  component: PlanComponent},
  {path:'/foo',      name: 'Foo',   component: FooComponent}
]}

UserComponent 中,我定义了另一条路由,如下所示:

@RouteConfig([
  {path:'/info',   name: 'UserInfo',   component: UserInfoComponent, useAsDefault: true},
  {path:'/order',  name: 'UserOrder',  component: UserOrderComponent},
  {path:'/detail', name: 'UserDetail', component: UserDetailComponent}
]}

AppComponentUserComponent 中定义了 2 个独立的导航:

//AppComponent:
  <a [routerLink]="['User']">User</a>
  <a [routerLink]="['Plan']">Plan</a>
  <a [routerLink]="['Foo']">Foo</a>
--------------------------------------------
//UserComponent:
  <a [routerLink]="['UserInfo']">User Info</a>
  <a [routerLink]="['UserOrder']">User Order</a>
  <a [routerLink]="['UserDetail']">User Detail</a>

我期望的行为是:
当用户点击这些导航时,会出现一个模式,询问用户是否在离开该路线之前确认保存。如果是,则自动保存用户的更改。

由于在UserComponent中好像没有办法得到这些变化,所以我想把逻辑放到这些子组件中(UserInfoComponent, UserOrderComponentUserDetailComponent)。那么有什么方法可以在用户离开子组件内的当前路由时触发回调?如果没有,是否有其他方法可以实现?谢谢

最佳答案

路由器已经自带lifecycle hooks , CanDeactivate Interface

允许/拒绝导航离开的 Hook 是 routerCanDeactivate(nextInstruction, prevInstruction) { ... }。如果您从此函数返回 false,它将停止导航。

示例 With Plunker : (在 plunker 中,route 2 将永远不允许导航离开。你不能返回到 route 1)

@Component({
  selector:'route-2',
  template:'route 2 template'
})
class SecondRoute{
  routerCanDeactivate(){
    return false; // false stops navigation, true continue navigation
  }
}

关于javascript - Angular 2 : How to apply a callback when I leave a route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36415101/

相关文章:

li标签onclick位置的Javascript

导航后 Angular 2 View 没有响应

javascript - Angular 2路由器导航到另一个url时不重置 socket

javascript - 通过多个模板渲染主干 View

javascript - 在月份/日期选择器上限制年份

javascript - 使用 interact.js + SVG 中的句柄调整大小

Angular 2 @Input 经常被调用

javascript - 让函数在点击时运行

Angular.io 拦截器与服务 worker

angular - 在 Angular 2 中使用订阅获取 http 响应后获取 [object Object]