My Angular 2 app has a logout feature. We want to avoid doing a page reload if we can (i.e. document.location.href = '/';
), but the logout process needs to reset the app so when another user logs in there's no residual data from the previous session.
Here's our main.ts file:
import 'es6-shim/es6-shim';
import './polyfills';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { ComponentRef, enableProdMode } from '@angular/core';
import { environment } from '@environment';
import { AppModule } from './app/app.module';
if (environment.production === true) {
enableProdMode();
}
const init = () => {
platformBrowserDynamic().bootstrapModule(AppModule)
.then(() => (<any>window).appBootstrap && (<any>window).appBootstrap())
.catch(err => console.error(err));
};
init();
platformBrowserDynamic().onDestroy(() => {
init();
});
You can see that I'm trying to call the init() method when the application is destroyed. The logout method in our user-authentication.service initiates destroy:
logout() {
this.destroyAuthToken();
this.setLoggedIn(false);
this.navigateToLogin()
.then(() => {
platformBrowserDynamic().destroy();
});
}
This gives the following error:
The selector "app-root" did not match any elements
Any help appreciated.
I came across the same issue. A simpler way is to use location.reload()
The function in your App.component which is called when the user clicks the logout button should look like this.
I ended up figuring this out in the end. This could be done more simply than my implementation, but I wanted to keep the bootstrapping in
main.ts
rather than stick it in the service that requests the restart.main.ts
) to communicate:boot-control.ts
:main.ts
to subscribe to the reboot request:main.ts
:user-auth.service.ts
:The NgZone requirement is to avoid the error: