angular - get current route component instance or guards -
i have navigation area including logout button next router-outlet.
app.component.html:
<my-nav-header></my-nav-header> <router-outlet></router-outlet>
on every module/component in router have implemented candeactivate method dirty-checking (as described in routing & naviagtion tutorial of angular) called actual candeactivateguard via interface described in tutorial. works expected - when user clicks router link , has unsaved changes asked whether route anyway or not.
my-nav-header.component.ts
logoutbtnclick(){ // todo: insert call candeactivate here // or find way dirty state of current component in router //console.debug('logout - can deactivate[1]: ', this.activatedroute.routeconfig.candeactivate); //console.debug('logout - can deactivate[2]: ', this.activatedroute.snapshot.routeconfig.candeactivate); this.loginsvc.dologout(); }
login.service.ts
@injectable() export class loginservice { ... public dologout(){ this.myhttp.sendlogout().subscribe( ()=> { this.clearsessiondata(); this.myhttp.clearsessiondata(); this.router.navigate(['/login']); // triggering candeactivate, late logout command has been sent server }
when user presses logout button want dirty check executed (giving user possibility cancel logout) before logout method sends logout command server.
i have tried inject both router
, activatedroute
navigation header component, in both cases rootconfig property null preventing me accessing candeactivate.
so question is: how access either candeactivate guard of current route or instance of current route component itself?
the candeactivate
class takes type of component checking on. defining interface component has candeactivate method can check if method exists , conditionally call on active component if implements method. otherwise can return true , allow component deactivated;
interface icancomponentdeactivate extends component { candeactivate: () => observable<boolean> | boolean; } export class candeactivateguard implements candeactivate<icancomponentdeactivate> { public candeactivate(currentcomponent: icancomponentdeactivate, route: activatedroutesnapshot, state: routerstatesnapshot): observable<boolean> | boolean { return currentcomponent.candeactivate ? currentcomponent.candeactivate() : true; } }
Comments
Post a Comment