Angular 2:当我离开路线时如何应用回调

时间:2016-04-05 00:24:08

标签: javascript angular angular2-routing

以下是示例,我在@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} ]} 我有另一条定义如下的路线:

AppComponent

UserComponent//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中获取这些更改,因此我想将逻辑放入这些子组件(UserOrderComponentUserDetailComponentecho $PATH )。那么,当用户将当前路由留在子组件内时,有什么方法可以触发回调?如果没有,有没有其他方法来实现这一目标?感谢

1 个答案:

答案 0 :(得分:5)

路由器已附带lifecycle hooksCanDeactivate Interface

允许/拒绝导航的钩子是@Component({ selector:'route-2', template:'route 2 template' }) class SecondRoute{ routerCanDeactivate(){ return false; // false stops navigation, true continue navigation } } 。如果从此函数返回false,它将停止导航。

示例With Plunker :(在弹道中,路线2永远不会允许导航。你不能回到路线1)

SELECT 
*
FROM 
(
SELECT 
page,   
count(page) countOfTable1
FROM table1
WHERE date = '2016-04-04'
GROUP BY page) firstTable

INNER JOIN 
(
SELECT 
page,   
count(page) countOfTable2
FROM table2
WHERE date = '2016-04-04'
GROUP BY page ) secondTable
ON firstTable.page = secondTable.page ;