Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Create a singleton that provides a way for Angular and non-Angular (main.ts) to communicate:
- boot-control.ts:
- import { Observable } from 'rxjs/Observable';
- import { Subject } from 'rxjs/Subject';
- export class BootController {
- private static instance: BootController;
- private _reboot: Subject<boolean> = new Subject();
- private reboot$ = this._reboot.asObservable();
- static getbootControl() {
- if (!BootController.instance) {
- BootController.instance = new BootController();
- }
- return BootController.instance;
- }
- public watchReboot() {
- return this.reboot$;
- }
- public restart() {
- this._reboot.next(true);
- }
- }
- Adjust main.ts to subscribe to the reboot request:
- main.ts:
- import { enableProdMode, NgModuleRef, NgModule } from '@angular/core';
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
- import { AppModule } from './app/app.module';
- import { environment } from './environments/environment';
- import { BootController } from './boot-control';
- if (environment.production) {
- enableProdMode();
- }
- const init = () => {
- platformBrowserDynamic().bootstrapModule(AppModule)
- .then(() => (<any>window).appBootstrap && (<any>window).appBootstrap())
- .catch(err => console.error('NG Bootstrap Error =>', err));
- }
- // Init on first load
- init();
- // Init on reboot request
- const boot = BootController.getbootControl().watchReboot().subscribe(() => init());
- Add NgZone to the service that triggers the logout:
- user-auth.service.ts:
- import { BootController } from '@app/../boot-control';
- import { Injectable, NgZone } from '@angular/core';
- @Injectable()
- export class UserAuthenticationService {
- constructor (
- private ngZone: NgZone,
- private router: Router
- ) {...}
- logout() {
- // Removes auth token kept in local storage (not strictly relevant to this demo)
- this.removeAuthToken();
- // Triggers the reboot in main.ts
- this.ngZone.runOutsideAngular(() => BootController.getbootControl().restart());
- // Navigate back to login
- this.router.navigate(['login']);
- }
- }
- The NgZone requirement is to avoid the error:
- Expected to not be in Angular Zone, but it is!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement