编程语言
首页 > 编程语言> > javascript – Angular 2:当我离开路线时如何应用回调

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

作者:互联网

这是一个例子,我在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}
]}

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,UserOrderComponent和UserDetailComponent).那么,当用户将当前路由留在子组件内时,有什么方法可以触发回调?如果没有,有没有其他方法来实现这一目标?谢谢

解决方法:

路由器已经配备lifecycle hooks,CanDeactivate Interface

允许/拒绝导航的钩子是routerCanDeactivate(nextInstruction,prevInstruction){…}.如果从此函数返回false,它将停止导航.

With Plunker :(在探测器中,路线2永远不会允许导航.你不能回到路线1)

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

标签:javascript,angular2-routing,angular
来源: https://codeday.me/bug/20190608/1200819.html