Advertisement
paulozagaloneves

Resetting Angular 2+ Application on logout

Jan 18th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2.     Create a singleton that provides a way for Angular and non-Angular (main.ts) to communicate:
  3.  
  4. boot-control.ts:
  5.  
  6. import { Observable } from 'rxjs/Observable';
  7. import { Subject } from 'rxjs/Subject';
  8. export class BootController {
  9.   private static instance: BootController;
  10.   private _reboot: Subject<boolean> = new Subject();
  11.   private reboot$ = this._reboot.asObservable();
  12.  
  13.   static getbootControl() {
  14.     if (!BootController.instance) {
  15.       BootController.instance = new BootController();
  16.     }
  17.     return BootController.instance;
  18.   }
  19.  
  20.   public watchReboot() {
  21.     return this.reboot$;
  22.   }
  23.  
  24.   public restart() {
  25.     this._reboot.next(true);
  26.   }
  27. }
  28.  
  29.     Adjust main.ts to subscribe to the reboot request:
  30.  
  31. main.ts:
  32.  
  33. import { enableProdMode, NgModuleRef, NgModule } from '@angular/core';
  34. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  35. import { AppModule } from './app/app.module';
  36. import { environment } from './environments/environment';
  37. import { BootController } from './boot-control';
  38.  
  39. if (environment.production) {
  40.   enableProdMode();
  41. }
  42.  
  43. const init = () => {
  44.   platformBrowserDynamic().bootstrapModule(AppModule)
  45.   .then(() => (<any>window).appBootstrap && (<any>window).appBootstrap())
  46.   .catch(err => console.error('NG Bootstrap Error =>', err));
  47. }
  48.  
  49. // Init on first load
  50. init();
  51.  
  52. // Init on reboot request
  53. const boot = BootController.getbootControl().watchReboot().subscribe(() => init());
  54.  
  55.     Add NgZone to the service that triggers the logout:
  56.  
  57. user-auth.service.ts:
  58.  
  59. import { BootController } from '@app/../boot-control';
  60. import { Injectable, NgZone } from '@angular/core';
  61.  
  62. @Injectable()
  63. export class UserAuthenticationService {
  64.     constructor (
  65.         private ngZone: NgZone,
  66.         private router: Router
  67.     ) {...}
  68.  
  69.     logout() {
  70.         // Removes auth token kept in local storage (not strictly relevant to this demo)
  71.         this.removeAuthToken();
  72.  
  73.         // Triggers the reboot in main.ts        
  74.         this.ngZone.runOutsideAngular(() => BootController.getbootControl().restart());
  75.  
  76.         // Navigate back to login
  77.         this.router.navigate(['login']);
  78.     }
  79. }
  80.  
  81. The NgZone requirement is to avoid the error:
  82.  
  83.     Expected to not be in Angular Zone, but it is!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement