watch for browser back button press and update

This commit is contained in:
Fran Jurmanović
2021-05-29 21:33:07 +02:00
parent fdb3eb5a0f
commit 1c346346f2
4 changed files with 18 additions and 8 deletions

View File

@@ -25,11 +25,11 @@ class AppMainElement extends HTMLElement {
path: "/",
component: "home-page",
layout: "menu-layout",
middleware: this.middleAuth,
},
{
path: "/home",
component: "home-page",
middleware: this.isAuth,
},
{
path: "/rb",
@@ -47,12 +47,16 @@ class AppMainElement extends HTMLElement {
this.routerService.init();
}
isAuth = () => {
if (this.authStore?.token == null) {
middleAuth = () => {
if (!this.isAuth) {
this.routerService.goTo("/unauthorized");
return true;
}
};
get isAuth(): boolean {
return this.authStore && this.authStore.token;
}
}
export type { AppMainElement };

View File

@@ -40,10 +40,8 @@ class RouterService {
}
let changed: boolean = false;
if (_mainRoot?.childNodes.length > 0) {
console.log(_mainRoot.childNodes);
_mainRoot?.childNodes?.forEach?.(
(child: BaseLayoutElement) => {
console.log("Eh");
if (
route.layout &&
route.layout.toUpperCase() === child.tagName &&
@@ -101,9 +99,10 @@ class RouterService {
_mainRoot.innerHTML = "404 - Not found";
}
@update
goTo(path: string) {
if (!Array.isArray(this.historyStack)) this.historyStack = [];
const currentPath = window.location.pathname;
if (path == currentPath) return;
const _index = this._routes.findIndex((route) => route.path === path);
if (_index >= 0) {
const newRoute = this._routes[_index];
@@ -111,6 +110,7 @@ class RouterService {
const url = new URL(window.location.toString());
url.pathname = path;
window.history.pushState({}, "", url.toString());
this.update();
}
}
@@ -128,7 +128,11 @@ class RouterService {
}
@update
init() {}
init() {
window.addEventListener("popstate", () => {
this.update();
});
}
}
class RouteState {

View File

@@ -11,6 +11,8 @@ class AuthStore {
}
get token() {
if (this._token == "null") return null;
if (this._token == "undefined") return undefined;
return this._token;
}

View File

@@ -14,7 +14,7 @@ class HomePageElement extends HTMLElement {
@update
connectedCallback() {
this.pingService = new PingService(this.appMain?.appService);
this.getPong();
if (this.appMain.isAuth) this.getPong();
}
getPong = async () => {