Skip to content

Instantly share code, notes, and snippets.

@tuckerjt07
Last active March 22, 2024 14:38
Show Gist options
  • Save tuckerjt07/8c8c7fd55208c4c23f8adb0750e15ee8 to your computer and use it in GitHub Desktop.
Save tuckerjt07/8c8c7fd55208c4c23f8adb0750e15ee8 to your computer and use it in GitHub Desktop.
Base application router module
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginHostComponent } from './login-host/login-host.component';
import { CatalogHostComponent } from './catalog-host/catalog-host.component';
const routes: Routes = [
{ path: 'catalog', component: CatalogHostComponent },
{ path: 'login', component: LoginHostComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class HostLocationService {
constructor(private router: Router) { }
public handleNavigation() {
this.router.events.subscribe((val) => {
if (val instanceof NavigationStart) {
console.log('Prenav', val);
if (val.id === 1 && val.navigationTrigger === 'imperative' || val.navigationTrigger === 'popstate') {
// Get URL from current Route
const fullRouteUrl = val.url;
// Remove outlet from url
const routeWithoutOutlet = fullRouteUrl.replace(/ *\([^)]*\) */g, '');
console.log(`fullRouteUrl: ${fullRouteUrl} routeWithoutOutlet: ${routeWithoutOutlet}`);
// Navigate to host route and replace location history with fullRouteUrl
this.router.navigateByUrl(routeWithoutOutlet).then(() => {
window.history.pushState({}, null, fullRouteUrl);
});
}
}
});
}
}
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Store } from '@ngxs/store';
import { SuccessfulAuthResponse } from '../core/auth/state/auth.state.model';
import { IAuthStateModel } from '../core/auth/interfaces/IAuthStateModel';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthState } from '../core/auth/state/auth.state';
@Component({
selector: 'login-host',
templateUrl: './login-host.component.html',
styleUrls: ['./login-host.component.scss'],
encapsulation: ViewEncapsulation.Emulated
})
export class LoginHostComponent implements OnInit {
bambooRoseAuthenticationUrl = 'someUrl';
isMobileDevice = false;
elementUrl = 'http://localhost:8082/login-element@0.0.0.js';
constructor(private store: Store, private activeRoute: ActivatedRoute, private router: Router) { }
ngOnInit() {
}
authResponse($event: CustomEvent) {
this.store.dispatch(new SuccessfulAuthResponse($event.detail as IAuthStateModel));
console.log(this.store.selectSnapshot(AuthState.rawToken));
this.activeRoute.queryParams.subscribe((queryParams) => {
this.router.navigateByUrl('/catalog');
});
}
}
import { NgModule } from '@angular/core';
import { Routes } from '@angular/router';
import { CatalogHomeComponent } from './catalog-home/catalog-home.component';
import { ProductDetailsComponent } from './product-details/product-details.component';
import { ElementRoutingModule } from './core/custom-routing/element-routing.module';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const routes: Routes = [
{
path: 'catalog',
component: CatalogHomeComponent,
outlet: 'catalog'
},
{
path: 'productDetails',
component: ProductDetailsComponent,
outlet: 'catalog'
},
{
path: '',
outlet: 'catalog',
component: PageNotFoundComponent
},
{
path: '**',
redirectTo: '',
pathMatch: 'full'
}
];
@NgModule({
imports: [ElementRoutingModule.withRoutes(routes)],
exports: [ElementRoutingModule]
})
export class AppRoutingModule {}
import { MultiLocationStrategy } from './multi-location-strategy';
import {
NgModule,
NgModuleFactoryLoader,
Compiler,
Injector,
Optional,
ModuleWithProviders,
SystemJsNgModuleLoader
} from '@angular/core';
import {
RouterModule,
Router,
UrlSerializer,
ChildrenOutletContexts,
ROUTES,
ROUTER_CONFIGURATION,
UrlHandlingStrategy,
PreloadingStrategy,
NoPreloading,
provideRoutes,
Routes,
ExtraOptions,
Route
} from '@angular/router';
import { ɵROUTER_PROVIDERS as ROUTER_PROVIDERS } from '@angular/router';
import { LocationStrategy, Location } from '@angular/common';
import { flatten } from '@angular/compiler';
export function setupElementsRouter(
urlSerializer: UrlSerializer,
contexts: ChildrenOutletContexts,
location: Location,
loader: NgModuleFactoryLoader,
compiler: Compiler,
injector: Injector,
routes: Route[][],
opts?: ExtraOptions,
urlHandlingStrategy?: UrlHandlingStrategy
): Router {
// tslint:disable-next-line:no-non-null-assertion
return new Router(
null!,
urlSerializer,
contexts,
location,
injector,
loader,
compiler,
flatten(routes)
);
}
@NgModule({
exports: [RouterModule],
providers: [
ROUTER_PROVIDERS,
{ provide: Location, useClass: Location },
{ provide: LocationStrategy, useClass: MultiLocationStrategy },
{ provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader },
{
provide: Router,
useFactory: setupElementsRouter,
deps: [
UrlSerializer,
ChildrenOutletContexts,
Location,
NgModuleFactoryLoader,
Compiler,
Injector,
ROUTES,
ROUTER_CONFIGURATION,
[UrlHandlingStrategy, new Optional()]
]
},
{ provide: PreloadingStrategy, useExisting: NoPreloading },
provideRoutes([])
]
})
export class ElementRoutingModule {
static withRoutes(
routes: Routes,
config?: ExtraOptions
): ModuleWithProviders<ElementRoutingModule> {
return {
ngModule: ElementRoutingModule,
providers: [
provideRoutes(routes),
{ provide: ROUTER_CONFIGURATION, useValue: config ? config : {} }
]
};
}
}
import { Injectable } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class HostLocationService {
constructor(private router: Router) {}
public handleNavigation() {
this.router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
console.log(val);
window.history.pushState({}, null, val.url);
}
});
}
}
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-page-not-found',
templateUrl: './page-not-found.component.html',
styleUrls: ['./page-not-found.component.scss']
})
export class PageNotFoundComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
this.router.navigate([{ outlets: { primary: 'catalog', catalog: 'productDetails' } }]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment