├── src
├── assets
│ └── .gitkeep
├── app
│ ├── app.component.css
│ ├── about
│ │ ├── about.component.css
│ │ ├── about.component.html
│ │ ├── about.component.spec.ts
│ │ └── about.component.ts
│ ├── home
│ │ ├── home.component.css
│ │ ├── home.component.html
│ │ ├── home.component.ts
│ │ └── home.component.spec.ts
│ ├── lazy
│ │ ├── lazy.component.css
│ │ ├── lazy.component.html
│ │ ├── lazy.component.spec.ts
│ │ └── lazy.component.ts
│ ├── lazy2
│ │ ├── lazy.component.css
│ │ ├── lazy.component.html
│ │ ├── lazy2.component.ts
│ │ └── lazy.component.spec.ts
│ ├── app.component.html
│ ├── app.module.ts
│ ├── app.component.ts
│ └── app.component.spec.ts
├── styles.css
├── environments
│ ├── environment.prod.ts
│ └── environment.ts
├── favicon.ico
├── index.html
├── main.ts
├── test.ts
└── polyfills.ts
├── ngconf2020-reactive-router.pdf
├── projects
└── router
│ ├── tsconfig.lib.prod.json
│ ├── ng-package.json
│ ├── src
│ ├── lib
│ │ ├── route-params.service.ts
│ │ ├── url-parser.ts
│ │ ├── route.ts
│ │ ├── router.module.ts
│ │ ├── router.service.ts
│ │ ├── link.component.ts
│ │ ├── route.component.ts
│ │ └── router.component.ts
│ ├── public-api.ts
│ └── test.ts
│ ├── package.json
│ ├── tslint.json
│ ├── tsconfig.spec.json
│ ├── tsconfig.lib.json
│ ├── README.md
│ └── karma.conf.js
├── e2e
├── tsconfig.json
├── src
│ ├── app.po.ts
│ └── app.e2e-spec.ts
└── protractor.conf.js
├── tsconfig.app.json
├── .editorconfig
├── tsconfig.spec.json
├── browserslist
├── .gitignore
├── tsconfig.json
├── README.md
├── karma.conf.js
├── package.json
├── tslint.json
└── angular.json
/src/assets/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/app.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/about/about.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/home/home.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/lazy/lazy.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/lazy2/lazy.component.css:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/home/home.component.html:
--------------------------------------------------------------------------------
1 |
home works!
2 |
--------------------------------------------------------------------------------
/src/app/about/about.component.html:
--------------------------------------------------------------------------------
1 | about works!
2 |
3 | {{ me$ | async }}
--------------------------------------------------------------------------------
/src/styles.css:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 |
--------------------------------------------------------------------------------
/src/environments/environment.prod.ts:
--------------------------------------------------------------------------------
1 | export const environment = {
2 | production: true
3 | };
4 |
--------------------------------------------------------------------------------
/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/brandonroberts/ngconf2020-reactive-router/HEAD/src/favicon.ico
--------------------------------------------------------------------------------
/src/app/lazy2/lazy.component.html:
--------------------------------------------------------------------------------
1 |
2 | lazy 2 works!
3 |
4 | Go Home
5 |
6 |
--------------------------------------------------------------------------------
/ngconf2020-reactive-router.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/brandonroberts/ngconf2020-reactive-router/HEAD/ngconf2020-reactive-router.pdf
--------------------------------------------------------------------------------
/projects/router/tsconfig.lib.prod.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.lib.json",
3 | "angularCompilerOptions": {
4 | "enableIvy": false
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/projects/router/ng-package.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
3 | "dest": "../../dist/router",
4 | "lib": {
5 | "entryFile": "src/public-api.ts"
6 | }
7 | }
--------------------------------------------------------------------------------
/projects/router/src/lib/route-params.service.ts:
--------------------------------------------------------------------------------
1 | import { Observable } from 'rxjs';
2 |
3 | export interface Params {
4 | [param: string]: any;
5 | }
6 |
7 | export class RouteParams extends Observable {}
--------------------------------------------------------------------------------
/projects/router/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "router",
3 | "version": "0.0.1",
4 | "peerDependencies": {
5 | "@angular/common": "^9.0.3",
6 | "@angular/core": "^9.0.3",
7 | "tslib": "^1.10.0"
8 | }
9 | }
--------------------------------------------------------------------------------
/projects/router/src/lib/url-parser.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 |
3 | @Injectable()
4 | export class UrlParser {
5 | parse(url: string, base?: string | URL): URL {
6 | return new URL(url, base);
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/app/lazy/lazy.component.html:
--------------------------------------------------------------------------------
1 |
2 | lazy works!
3 |
4 | Go Lazy 2
5 | Go Home
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/e2e/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/e2e",
5 | "module": "commonjs",
6 | "target": "es5",
7 | "types": [
8 | "jasmine",
9 | "jasminewd2",
10 | "node"
11 | ]
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "./out-tsc/app",
5 | "types": []
6 | },
7 | "files": [
8 | "src/main.ts",
9 | "src/polyfills.ts"
10 | ],
11 | "include": [
12 | "src/**/*.d.ts"
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see https://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | max_line_length = off
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/projects/router/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tslint.json",
3 | "rules": {
4 | "directive-selector": [
5 | true,
6 | "attribute",
7 | "lib",
8 | "camelCase"
9 | ],
10 | "component-selector": [
11 | true,
12 | "element",
13 | "lib",
14 | "kebab-case"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/projects/router/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../../out-tsc/spec",
5 | "types": [
6 | "jasmine",
7 | "node"
8 | ]
9 | },
10 | "files": [
11 | "src/test.ts"
12 | ],
13 | "include": [
14 | "**/*.spec.ts",
15 | "**/*.d.ts"
16 | ]
17 | }
18 |
--------------------------------------------------------------------------------
/src/app/home/home.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 |
3 | @Component({
4 | selector: 'app-home',
5 | templateUrl: './home.component.html',
6 | styleUrls: ['./home.component.css']
7 | })
8 | export class HomeComponent implements OnInit {
9 |
10 | constructor() { }
11 |
12 | ngOnInit(): void {
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/e2e/src/app.po.ts:
--------------------------------------------------------------------------------
1 | import { browser, by, element } from 'protractor';
2 |
3 | export class AppPage {
4 | navigateTo(): Promise {
5 | return browser.get(browser.baseUrl) as Promise;
6 | }
7 |
8 | getTitleText(): Promise {
9 | return element(by.css('app-root .content span')).getText() as Promise;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "./out-tsc/spec",
5 | "types": [
6 | "jasmine",
7 | "node"
8 | ]
9 | },
10 | "files": [
11 | "src/test.ts",
12 | "src/polyfills.ts"
13 | ],
14 | "include": [
15 | "src/**/*.spec.ts",
16 | "src/**/*.d.ts"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Ngconf2020ReactiveRouter
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/projects/router/src/public-api.ts:
--------------------------------------------------------------------------------
1 | /*
2 | * Public API Surface of router
3 | */
4 |
5 | export * from './lib/router.service';
6 | export * from './lib/router.component';
7 | export * from './lib/route.component';
8 | export * from './lib/router.module';
9 | export * from './lib/route-params.service';
10 | export * from './lib/link.component';
11 | export * from './lib/url-parser';
12 |
--------------------------------------------------------------------------------
/projects/router/src/lib/route.ts:
--------------------------------------------------------------------------------
1 | import { Type } from '@angular/core';
2 |
3 | import { Params } from './route-params.service';
4 |
5 | export type LoadComponent = () => Promise>;
6 |
7 | export interface Route {
8 | path: string;
9 | component?: Type;
10 | loadComponent?: LoadComponent;
11 | matcher?: RegExp;
12 | }
13 |
14 | export interface ActiveRoute {
15 | route: Route;
16 | params: Params;
17 | }
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { enableProdMode } from '@angular/core';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 |
4 | import { AppModule } from './app/app.module';
5 | import { environment } from './environments/environment';
6 |
7 | if (environment.production) {
8 | enableProdMode();
9 | }
10 |
11 | platformBrowserDynamic().bootstrapModule(AppModule)
12 | .catch(err => console.error(err));
13 |
--------------------------------------------------------------------------------
/browserslist:
--------------------------------------------------------------------------------
1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
2 | # For additional information regarding the format and rule options, please see:
3 | # https://github.com/browserslist/browserslist#queries
4 |
5 | # You can see what browsers were selected by your queries by running:
6 | # npx browserslist
7 |
8 | > 0.5%
9 | last 2 versions
10 | Firefox ESR
11 | not dead
12 | not IE 9-11 # For IE 9-11 support, remove 'not'.
--------------------------------------------------------------------------------
/projects/router/tsconfig.lib.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../../out-tsc/lib",
5 | "target": "es2015",
6 | "declaration": true,
7 | "inlineSources": true,
8 | "types": [],
9 | "lib": [
10 | "dom",
11 | "es2018"
12 | ]
13 | },
14 | "angularCompilerOptions": {
15 | "skipTemplateCodegen": true,
16 | "strictMetadataEmit": true,
17 | "enableResourceInlining": true
18 | },
19 | "exclude": [
20 | "src/test.ts",
21 | "**/*.spec.ts"
22 | ]
23 | }
24 |
--------------------------------------------------------------------------------
/src/app/app.component.html:
--------------------------------------------------------------------------------
1 |
3 |
4 | Home
5 | About
6 | Lazy
7 | About 2
8 | About 3
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { BrowserModule } from '@angular/platform-browser';
2 | import { NgModule } from '@angular/core';
3 |
4 | import { AppComponent } from './app.component';
5 | import { RouterModule } from '@ngconf/router';
6 | import { HomeComponent } from './home/home.component';
7 | import { AboutComponent } from './about/about.component';
8 |
9 | @NgModule({
10 | declarations: [
11 | AppComponent,
12 | HomeComponent,
13 | AboutComponent
14 | ],
15 | imports: [
16 | BrowserModule,
17 | RouterModule.forRoot()
18 | ],
19 | bootstrap: [AppComponent]
20 | })
21 | export class AppModule { }
22 |
--------------------------------------------------------------------------------
/src/app/lazy2/lazy2.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { NgModule } from '@angular/core';
3 | import { CommonModule } from '@angular/common';
4 | import { RouterModule } from '@ngconf/router';
5 |
6 | @Component({
7 | selector: 'app-lazy',
8 | templateUrl: './lazy.component.html',
9 | styleUrls: ['./lazy.component.css'],
10 | })
11 | export class Lazy2Component implements OnInit {
12 | constructor() { }
13 |
14 | ngOnInit(): void {
15 | }
16 |
17 | }
18 |
19 | @NgModule({
20 | declarations: [Lazy2Component],
21 | imports: [
22 | CommonModule,
23 | RouterModule
24 | ]
25 | })
26 | export class LazyModule { }
27 |
--------------------------------------------------------------------------------
/src/app/home/home.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { HomeComponent } from './home.component';
4 |
5 | describe('HomeComponent', () => {
6 | let component: HomeComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ HomeComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(HomeComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/src/app/lazy/lazy.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { LazyComponent } from './lazy.component';
4 |
5 | describe('LazyComponent', () => {
6 | let component: LazyComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ LazyComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(LazyComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/src/app/lazy2/lazy.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { LazyComponent } from './lazy.component';
4 |
5 | describe('LazyComponent', () => {
6 | let component: LazyComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ LazyComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(LazyComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/src/environments/environment.ts:
--------------------------------------------------------------------------------
1 | // This file can be replaced during build by using the `fileReplacements` array.
2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
3 | // The list of file replacements can be found in `angular.json`.
4 |
5 | export const environment = {
6 | production: false
7 | };
8 |
9 | /*
10 | * For easier debugging in development mode, you can import the following file
11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
12 | *
13 | * This import should be commented out in production mode because it will have a negative impact
14 | * on performance if an error is thrown.
15 | */
16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
17 |
--------------------------------------------------------------------------------
/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { Component } from '@angular/core';
2 | import { HomeComponent } from './home/home.component';
3 | import { AboutComponent } from './about/about.component';
4 | import { Router } from '@ngconf/router';
5 |
6 | @Component({
7 | selector: 'app-root',
8 | templateUrl: './app.component.html',
9 | styleUrls: ['./app.component.css']
10 | })
11 | export class AppComponent {
12 | HomeComponent = HomeComponent;
13 | AboutComponent = AboutComponent;
14 | lazyComponent = () => import('./lazy/lazy.component').then(m => m.LazyComponent);
15 |
16 | constructor(private router: Router) {}
17 |
18 | goHome() {
19 | this.router.go('/');
20 | }
21 |
22 | goAbout() {
23 | this.router.go('/about');
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/app/about/about.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
2 |
3 | import { AboutComponent } from './about.component';
4 |
5 | describe('AboutComponent', () => {
6 | let component: AboutComponent;
7 | let fixture: ComponentFixture;
8 |
9 | beforeEach(async(() => {
10 | TestBed.configureTestingModule({
11 | declarations: [ AboutComponent ]
12 | })
13 | .compileComponents();
14 | }));
15 |
16 | beforeEach(() => {
17 | fixture = TestBed.createComponent(AboutComponent);
18 | component = fixture.componentInstance;
19 | fixture.detectChanges();
20 | });
21 |
22 | it('should create', () => {
23 | expect(component).toBeTruthy();
24 | });
25 | });
26 |
--------------------------------------------------------------------------------
/e2e/src/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { AppPage } from './app.po';
2 | import { browser, logging } from 'protractor';
3 |
4 | describe('workspace-project App', () => {
5 | let page: AppPage;
6 |
7 | beforeEach(() => {
8 | page = new AppPage();
9 | });
10 |
11 | it('should display welcome message', () => {
12 | page.navigateTo();
13 | expect(page.getTitleText()).toEqual('ngconf2020-reactive-router app is running!');
14 | });
15 |
16 | afterEach(async () => {
17 | // Assert that there are no errors emitted from the browser
18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER);
19 | expect(logs).not.toContain(jasmine.objectContaining({
20 | level: logging.Level.SEVERE,
21 | } as logging.Entry));
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/src/app/lazy/lazy.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit } from '@angular/core';
2 | import { NgModule } from '@angular/core';
3 | import { CommonModule } from '@angular/common';
4 | import { RouterModule } from '@ngconf/router';
5 | import { Lazy2Component } from '../lazy2/lazy2.component';
6 |
7 | @Component({
8 | selector: 'app-lazy',
9 | templateUrl: './lazy.component.html',
10 | styleUrls: ['./lazy.component.css'],
11 | })
12 | export class LazyComponent implements OnInit {
13 | lazy2Component = Lazy2Component;
14 |
15 | constructor() { }
16 |
17 | ngOnInit(): void {
18 | }
19 |
20 | }
21 |
22 | @NgModule({
23 | declarations: [LazyComponent],
24 | imports: [
25 | CommonModule,
26 | RouterModule
27 | ]
28 | })
29 | export class LazyModule { }
30 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 | # Only exists if Bazel was run
8 | /bazel-out
9 |
10 | # dependencies
11 | /node_modules
12 |
13 | # profiling files
14 | chrome-profiler-events*.json
15 | speed-measure-plugin*.json
16 |
17 | # IDEs and editors
18 | /.idea
19 | .project
20 | .classpath
21 | .c9/
22 | *.launch
23 | .settings/
24 | *.sublime-workspace
25 |
26 | # IDE - VSCode
27 | .vscode/*
28 | !.vscode/settings.json
29 | !.vscode/tasks.json
30 | !.vscode/launch.json
31 | !.vscode/extensions.json
32 | .history/*
33 |
34 | # misc
35 | /.sass-cache
36 | /connect.lock
37 | /coverage
38 | /libpeerconnection.log
39 | npm-debug.log
40 | yarn-error.log
41 | testem.log
42 | /typings
43 |
44 | # System Files
45 | .DS_Store
46 | Thumbs.db
47 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compileOnSave": false,
3 | "compilerOptions": {
4 | "baseUrl": "./",
5 | "outDir": "./dist/out-tsc",
6 | "sourceMap": true,
7 | "declaration": false,
8 | "downlevelIteration": true,
9 | "experimentalDecorators": true,
10 | "module": "esnext",
11 | "moduleResolution": "node",
12 | "importHelpers": true,
13 | "target": "es2015",
14 | "typeRoots": [
15 | "node_modules/@types"
16 | ],
17 | "lib": [
18 | "es2018",
19 | "dom"
20 | ],
21 | "paths": {
22 | "@ngconf/router": [
23 | "projects/router/src/public-api.ts",
24 | "dist/router/router",
25 | "dist/router"
26 | ]
27 | }
28 | },
29 | "angularCompilerOptions": {
30 | "fullTemplateTypeCheck": true,
31 | "strictInjectionParameters": true
32 | }
33 | }
--------------------------------------------------------------------------------
/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'zone.js/dist/zone-testing';
4 | import { getTestBed } from '@angular/core/testing';
5 | import {
6 | BrowserDynamicTestingModule,
7 | platformBrowserDynamicTesting
8 | } from '@angular/platform-browser-dynamic/testing';
9 |
10 | declare const require: {
11 | context(path: string, deep?: boolean, filter?: RegExp): {
12 | keys(): string[];
13 | (id: string): T;
14 | };
15 | };
16 |
17 | // First, initialize the Angular testing environment.
18 | getTestBed().initTestEnvironment(
19 | BrowserDynamicTestingModule,
20 | platformBrowserDynamicTesting()
21 | );
22 | // Then we find all the tests.
23 | const context = require.context('./', true, /\.spec\.ts$/);
24 | // And load the modules.
25 | context.keys().map(context);
26 |
--------------------------------------------------------------------------------
/projects/router/src/lib/router.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule, ModuleWithProviders } from '@angular/core';
2 | import { LocationStrategy, PathLocationStrategy } from '@angular/common';
3 |
4 | import { RouterComponent } from './router.component';
5 | import { RouteComponent } from './route.component';
6 | import { LinkTo } from './link.component';
7 | import { UrlParser } from './url-parser';
8 |
9 | const components = [
10 | RouterComponent,
11 | RouteComponent,
12 | LinkTo
13 | ];
14 |
15 | @NgModule({
16 | declarations: [components],
17 | exports: [components]
18 | })
19 | export class RouterModule {
20 |
21 | static forRoot(): ModuleWithProviders {
22 | return {
23 | ngModule: RouterModule,
24 | providers: [
25 | UrlParser,
26 | { provide: LocationStrategy, useClass: PathLocationStrategy }
27 | ]
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/projects/router/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'zone.js/dist/zone';
4 | import 'zone.js/dist/zone-testing';
5 | import { getTestBed } from '@angular/core/testing';
6 | import {
7 | BrowserDynamicTestingModule,
8 | platformBrowserDynamicTesting
9 | } from '@angular/platform-browser-dynamic/testing';
10 |
11 | declare const require: {
12 | context(path: string, deep?: boolean, filter?: RegExp): {
13 | keys(): string[];
14 | (id: string): T;
15 | };
16 | };
17 |
18 | // First, initialize the Angular testing environment.
19 | getTestBed().initTestEnvironment(
20 | BrowserDynamicTestingModule,
21 | platformBrowserDynamicTesting()
22 | );
23 | // Then we find all the tests.
24 | const context = require.context('./', true, /\.spec\.ts$/);
25 | // And load the modules.
26 | context.keys().map(context);
27 |
--------------------------------------------------------------------------------
/e2e/protractor.conf.js:
--------------------------------------------------------------------------------
1 | // @ts-check
2 | // Protractor configuration file, see link for more information
3 | // https://github.com/angular/protractor/blob/master/lib/config.ts
4 |
5 | const { SpecReporter } = require('jasmine-spec-reporter');
6 |
7 | /**
8 | * @type { import("protractor").Config }
9 | */
10 | exports.config = {
11 | allScriptsTimeout: 11000,
12 | specs: [
13 | './src/**/*.e2e-spec.ts'
14 | ],
15 | capabilities: {
16 | browserName: 'chrome'
17 | },
18 | directConnect: true,
19 | baseUrl: 'http://localhost:4200/',
20 | framework: 'jasmine',
21 | jasmineNodeOpts: {
22 | showColors: true,
23 | defaultTimeoutInterval: 30000,
24 | print: function() {}
25 | },
26 | onPrepare() {
27 | require('ts-node').register({
28 | project: require('path').join(__dirname, './tsconfig.json')
29 | });
30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
31 | }
32 | };
--------------------------------------------------------------------------------
/src/app/about/about.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit} from '@angular/core';
2 | import { RouteParams, Router } from '@ngconf/router';
3 | import { map } from 'rxjs/operators';
4 |
5 | @Component({
6 | selector: 'app-about',
7 | templateUrl: './about.component.html',
8 | styleUrls: ['./about.component.css']
9 | })
10 | export class AboutComponent implements OnInit {
11 | me$ = this.routeParams$.pipe(map(params => params['me']));
12 |
13 | constructor(private routeParams$: RouteParams, router: Router) {
14 | router.url$.subscribe(url => { console.log('rurl', url);});
15 | router.queryParams$.subscribe(qp => { console.log('rqp', qp);});
16 | router.hash$.subscribe(hash => { console.log('rh', hash);});
17 | routeParams$.subscribe(params => console.log('rp', params));
18 | }
19 |
20 | ngOnInit(): void {
21 | // console.log('on', this.routeParams);
22 | }
23 |
24 | ngAfterViewInit() {
25 | // console.log('after', this.routeParams);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/projects/router/README.md:
--------------------------------------------------------------------------------
1 | # Router
2 |
3 | This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.0.3.
4 |
5 | ## Code scaffolding
6 |
7 | Run `ng generate component component-name --project router` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project router`.
8 | > Note: Don't forget to add `--project router` or else it will be added to the default project in your `angular.json` file.
9 |
10 | ## Build
11 |
12 | Run `ng build router` to build the project. The build artifacts will be stored in the `dist/` directory.
13 |
14 | ## Publishing
15 |
16 | After building your library with `ng build router`, go to the dist folder `cd dist/router` and run `npm publish`.
17 |
18 | ## Running unit tests
19 |
20 | Run `ng test router` to execute the unit tests via [Karma](https://karma-runner.github.io).
21 |
22 | ## Further help
23 |
24 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
25 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ngconf2020ReactiveRouter
2 |
3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.0.4.
4 |
5 | ## Development server
6 |
7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
8 |
9 | ## Code scaffolding
10 |
11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
12 |
13 | ## Build
14 |
15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
16 |
17 | ## Running unit tests
18 |
19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
20 |
21 | ## Running end-to-end tests
22 |
23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
24 |
25 | ## Further help
26 |
27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
28 |
--------------------------------------------------------------------------------
/src/app/app.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed, async } from '@angular/core/testing';
2 | import { AppComponent } from './app.component';
3 |
4 | describe('AppComponent', () => {
5 | beforeEach(async(() => {
6 | TestBed.configureTestingModule({
7 | declarations: [
8 | AppComponent
9 | ],
10 | }).compileComponents();
11 | }));
12 |
13 | it('should create the app', () => {
14 | const fixture = TestBed.createComponent(AppComponent);
15 | const app = fixture.componentInstance;
16 | expect(app).toBeTruthy();
17 | });
18 |
19 | it(`should have as title 'ngconf2020-reactive-router'`, () => {
20 | const fixture = TestBed.createComponent(AppComponent);
21 | const app = fixture.componentInstance;
22 | expect(app.title).toEqual('ngconf2020-reactive-router');
23 | });
24 |
25 | it('should render title', () => {
26 | const fixture = TestBed.createComponent(AppComponent);
27 | fixture.detectChanges();
28 | const compiled = fixture.nativeElement;
29 | expect(compiled.querySelector('.content span').textContent).toContain('ngconf2020-reactive-router app is running!');
30 | });
31 | });
32 |
--------------------------------------------------------------------------------
/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, './coverage/ngconf2020-reactive-router'),
20 | reports: ['html', 'lcovonly', 'text-summary'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome'],
29 | singleRun: false,
30 | restartOnFileChange: true
31 | });
32 | };
33 |
--------------------------------------------------------------------------------
/projects/router/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, '../../coverage/router'),
20 | reports: ['html', 'lcovonly', 'text-summary'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome'],
29 | singleRun: false,
30 | restartOnFileChange: true
31 | });
32 | };
33 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ngconf2020-reactive-router",
3 | "version": "0.0.0",
4 | "scripts": {
5 | "ng": "ng",
6 | "start": "ng serve",
7 | "build": "ng build",
8 | "test": "ng test",
9 | "lint": "ng lint",
10 | "e2e": "ng e2e"
11 | },
12 | "private": true,
13 | "dependencies": {
14 | "@angular/animations": "~9.0.3",
15 | "@angular/common": "~9.0.3",
16 | "@angular/compiler": "~9.0.3",
17 | "@angular/core": "~9.0.3",
18 | "@angular/forms": "~9.0.3",
19 | "@angular/platform-browser": "~9.0.3",
20 | "@angular/platform-browser-dynamic": "~9.0.3",
21 | "@angular/router": "~9.0.3",
22 | "path-to-regexp": "^6.1.0",
23 | "rxjs": "~6.5.4",
24 | "tslib": "^1.10.0",
25 | "zone.js": "~0.10.2"
26 | },
27 | "devDependencies": {
28 | "@angular-devkit/build-angular": "~0.900.4",
29 | "@angular-devkit/build-ng-packagr": "~0.900.4",
30 | "@angular/cli": "~9.0.4",
31 | "@angular/compiler-cli": "~9.0.3",
32 | "@angular/language-service": "~9.0.3",
33 | "@types/jasmine": "~3.5.0",
34 | "@types/jasminewd2": "~2.0.3",
35 | "@types/node": "^12.11.1",
36 | "codelyzer": "^5.1.2",
37 | "jasmine-core": "~3.5.0",
38 | "jasmine-spec-reporter": "~4.2.1",
39 | "karma": "~4.3.0",
40 | "karma-chrome-launcher": "~3.1.0",
41 | "karma-coverage-istanbul-reporter": "~2.1.0",
42 | "karma-jasmine": "~2.0.1",
43 | "karma-jasmine-html-reporter": "^1.4.2",
44 | "ng-packagr": "^9.0.0",
45 | "protractor": "~5.4.3",
46 | "ts-node": "~8.3.0",
47 | "tslint": "~5.18.0",
48 | "typescript": "~3.7.5"
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "tslint:recommended",
3 | "rules": {
4 | "array-type": false,
5 | "arrow-parens": false,
6 | "deprecation": {
7 | "severity": "warning"
8 | },
9 | "component-class-suffix": true,
10 | "contextual-lifecycle": true,
11 | "directive-class-suffix": true,
12 | "directive-selector": [
13 | true,
14 | "attribute",
15 | "app",
16 | "camelCase"
17 | ],
18 | "component-selector": [
19 | true,
20 | "element",
21 | "app",
22 | "kebab-case"
23 | ],
24 | "import-blacklist": [
25 | true,
26 | "rxjs/Rx"
27 | ],
28 | "interface-name": false,
29 | "max-classes-per-file": false,
30 | "max-line-length": [
31 | true,
32 | 140
33 | ],
34 | "member-access": false,
35 | "member-ordering": [
36 | true,
37 | {
38 | "order": [
39 | "static-field",
40 | "instance-field",
41 | "static-method",
42 | "instance-method"
43 | ]
44 | }
45 | ],
46 | "no-consecutive-blank-lines": false,
47 | "no-console": [
48 | true,
49 | "debug",
50 | "info",
51 | "time",
52 | "timeEnd",
53 | "trace"
54 | ],
55 | "no-empty": false,
56 | "no-inferrable-types": [
57 | true,
58 | "ignore-params"
59 | ],
60 | "no-non-null-assertion": true,
61 | "no-redundant-jsdoc": true,
62 | "no-switch-case-fall-through": true,
63 | "no-var-requires": false,
64 | "object-literal-key-quotes": [
65 | true,
66 | "as-needed"
67 | ],
68 | "object-literal-sort-keys": false,
69 | "ordered-imports": false,
70 | "quotemark": [
71 | true,
72 | "single"
73 | ],
74 | "trailing-comma": false,
75 | "no-conflicting-lifecycle": true,
76 | "no-host-metadata-property": true,
77 | "no-input-rename": true,
78 | "no-inputs-metadata-property": true,
79 | "no-output-native": true,
80 | "no-output-on-prefix": true,
81 | "no-output-rename": true,
82 | "no-outputs-metadata-property": true,
83 | "template-banana-in-box": true,
84 | "template-no-negated-async": true,
85 | "use-lifecycle-interface": true,
86 | "use-pipe-transform-interface": true
87 | },
88 | "rulesDirectory": [
89 | "codelyzer"
90 | ]
91 | }
--------------------------------------------------------------------------------
/projects/router/src/lib/router.service.ts:
--------------------------------------------------------------------------------
1 | import { Injectable } from '@angular/core';
2 | import { PlatformLocation, LocationStrategy } from '@angular/common';
3 |
4 | import { BehaviorSubject } from 'rxjs';
5 | import { distinctUntilChanged } from 'rxjs/operators';
6 | import { UrlParser } from './url-parser';
7 |
8 | @Injectable({
9 | providedIn: 'root'
10 | })
11 | export class Router {
12 | private _url$ = new BehaviorSubject(this.getLocation());
13 | url$ = this._url$.pipe(distinctUntilChanged());
14 |
15 | private _queryParams$ = new BehaviorSubject({});
16 | queryParams$ = this._queryParams$.pipe(distinctUntilChanged());
17 |
18 | private _hash$ = new BehaviorSubject('');
19 | hash$ = this._hash$.pipe(distinctUntilChanged());
20 |
21 | constructor(
22 | private location: LocationStrategy,
23 | private platformLocation: PlatformLocation,
24 | private urlParser: UrlParser
25 | ) {
26 | this.location.onPopState(() => {
27 | this.nextState(this.getLocation());
28 | });
29 |
30 | this.nextState(this.getLocation());
31 | }
32 |
33 | go(url: string, queryParams: string = '') {
34 | this.location.pushState(null, '', this.location.prepareExternalUrl(url), queryParams);
35 |
36 | this.nextState(this.getLocation());
37 | }
38 |
39 | replace(url: string, queryParams?: string) {
40 | this.location.replaceState(null, '', this.location.prepareExternalUrl(url), queryParams);
41 |
42 | this.nextState(this.getLocation());
43 | }
44 |
45 | getExternalUrl(url: string) {
46 | return this.location.prepareExternalUrl(url);
47 | }
48 |
49 | private getLocation() {
50 | return this.platformLocation.href;
51 | }
52 |
53 | private nextState(url: string) {
54 | const parsedUrl = this._parseUrl(url);
55 | this._nextUrl(parsedUrl.pathname);
56 | this._nextQueryParams(parsedUrl.searchParams);
57 | this._nextHash(parsedUrl.hash ? parsedUrl.hash.split('#')[0] : '');
58 | }
59 |
60 | private _parseUrl(path: string): URL {
61 | return this.urlParser.parse(path);
62 | }
63 |
64 | private _nextUrl(url: string) {
65 | this._url$.next(url);
66 | }
67 |
68 | private _nextQueryParams(params: URLSearchParams) {
69 | this._queryParams$.next(params);
70 | }
71 |
72 | private _nextHash(hash: string) {
73 | this._hash$.next(hash);
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/projects/router/src/lib/link.component.ts:
--------------------------------------------------------------------------------
1 | import { Directive, HostBinding, HostListener, Input, Output, EventEmitter, Optional } from '@angular/core';
2 | import { Router } from './router.service';
3 | import { RouterComponent } from './router.component';
4 |
5 | /**
6 | * The LinkTo directive links to routes in your app
7 | *
8 | * Links are pushed to the `Router` service to trigger a route change.
9 | * Query params can be represented as an object or a string of names/values
10 | *
11 | * Home Page
12 | * Page 1
13 | */
14 | @Directive({ selector: '[linkTo]' })
15 | export class LinkTo {
16 | @Input() target: string;
17 | @HostBinding('href') linkHref;
18 |
19 | @Input() set linkTo(href: string){
20 | this._href = href;
21 | this._updateHref();
22 | }
23 |
24 | @Input() set queryParams(params: string) {
25 | this._query = params;
26 | this._updateHref();
27 | }
28 |
29 | @Output() hrefUpdated: EventEmitter = new EventEmitter();
30 |
31 | private _href: string;
32 | private _query: string;
33 |
34 | constructor(private router: Router, @Optional() private routerComp: RouterComponent) {}
35 |
36 | /**
37 | * Handles click events on the associated link
38 | * Prevents default action for non-combination click events without a target
39 | */
40 | @HostListener('click', ['$event'])
41 | onClick(event) {
42 | if (!this._comboClick(event) && !this.target) {
43 | this.router.go(this._href, this._query);
44 |
45 | event.preventDefault();
46 | }
47 | }
48 |
49 | private _updateHref() {
50 | let path = this._cleanUpHref(this._href);
51 |
52 | this.linkHref = this.router.getExternalUrl(path);
53 | this.hrefUpdated.emit(this.linkHref);
54 | }
55 |
56 | /**
57 | * Determines whether the click event happened with a combination of other keys
58 | */
59 | private _comboClick(event) {
60 | let buttonEvent = event.which || event.button;
61 |
62 | return (buttonEvent > 1 || event.ctrlKey || event.metaKey || event.shiftKey);
63 | }
64 |
65 | private _cleanUpHref(href: string = ''): string {
66 | // Check for trailing slashes in the path
67 | while (href.length > 1 && href.substr(-1) === '/') {
68 | // Remove trailing slashes
69 | href = href.substring(0, href.length - 1);
70 | }
71 |
72 | return href;
73 | }
74 | }
--------------------------------------------------------------------------------
/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This file includes polyfills needed by Angular and is loaded before the app.
3 | * You can add your own extra polyfills to this file.
4 | *
5 | * This file is divided into 2 sections:
6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
8 | * file.
9 | *
10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
13 | *
14 | * Learn more in https://angular.io/guide/browser-support
15 | */
16 |
17 | /***************************************************************************************************
18 | * BROWSER POLYFILLS
19 | */
20 |
21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */
22 | // import 'classlist.js'; // Run `npm install --save classlist.js`.
23 |
24 | /**
25 | * Web Animations `@angular/platform-browser/animations`
26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
28 | */
29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
30 |
31 | /**
32 | * By default, zone.js will patch all possible macroTask and DomEvents
33 | * user can disable parts of macroTask/DomEvents patch by setting following flags
34 | * because those flags need to be set before `zone.js` being loaded, and webpack
35 | * will put import in the top of bundle, so user need to create a separate file
36 | * in this directory (for example: zone-flags.ts), and put the following flags
37 | * into that file, and then add the following code before importing zone.js.
38 | * import './zone-flags';
39 | *
40 | * The flags allowed in zone-flags.ts are listed here.
41 | *
42 | * The following flags will work for all browsers.
43 | *
44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
47 | *
48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge
50 | *
51 | * (window as any).__Zone_enable_cross_context_check = true;
52 | *
53 | */
54 |
55 | /***************************************************************************************************
56 | * Zone JS is required by default for Angular itself.
57 | */
58 | import 'zone.js/dist/zone'; // Included with Angular CLI.
59 |
60 |
61 | /***************************************************************************************************
62 | * APPLICATION IMPORTS
63 | */
64 |
--------------------------------------------------------------------------------
/projects/router/src/lib/route.component.ts:
--------------------------------------------------------------------------------
1 | import {
2 | Component,
3 | OnInit,
4 | Input,
5 | Type,
6 | ViewChild,
7 | ElementRef,
8 | Injector,
9 | ɵrenderComponent as renderComponent,
10 | ɵmarkDirty as markDirty,
11 | ɵcreateInjector as createInjector
12 | } from "@angular/core";
13 |
14 | import { Subject, BehaviorSubject, merge, of } from "rxjs";
15 | import { tap, distinctUntilChanged, filter, takeUntil, mergeMap } from "rxjs/operators";
16 |
17 | import { LoadComponent, Route } from "./route";
18 | import { RouteParams, Params } from "./route-params.service";
19 | import { RouterComponent } from "./router.component";
20 |
21 |
22 | @Component({
23 | selector: "route",
24 | template: `
25 |
26 | `
27 | })
28 | export class RouteComponent implements OnInit {
29 | private destroy$ = new Subject();
30 | @ViewChild("outlet", { read: ElementRef, static: true }) outlet: ElementRef;
31 | @Input() path: string;
32 | @Input() component: Type;
33 | @Input() loadComponent: LoadComponent;
34 | route!: Route;
35 | rendered = null;
36 | private _routeParams$ = new BehaviorSubject({});
37 | routeParams$ = this._routeParams$.asObservable();
38 |
39 | constructor(private injector: Injector, private router: RouterComponent) {}
40 |
41 | ngOnInit(): void {
42 | // account for root level routes, don't add the basePath
43 | const path = this.router.parentRouterComponent
44 | ? this.router.basePath + this.path
45 | : this.path;
46 |
47 | this.route = this.router.registerRoute({
48 | path,
49 | component: this.component,
50 | loadComponent: this.loadComponent
51 | });
52 |
53 | const activeRoute$ = this.router.activeRoute$
54 | .pipe(
55 | filter(ar => ar !== null),
56 | distinctUntilChanged(),
57 | mergeMap(current => {
58 | if (current.route === this.route) {
59 | this._routeParams$.next(current.params);
60 |
61 | if (!this.rendered) {
62 | return this.loadAndRenderRoute(current.route);
63 | }
64 | } else if (this.rendered) {
65 | return of(this.clearView());
66 | }
67 |
68 | return of(null);
69 | })
70 | );
71 |
72 | const routeParams$ = this._routeParams$
73 | .pipe(
74 | distinctUntilChanged(),
75 | filter(() => !!this.rendered),
76 | tap(() => markDirty(this.rendered))
77 | );
78 |
79 | merge(activeRoute$, routeParams$).pipe(
80 | takeUntil(this.destroy$),
81 | ).subscribe();
82 | }
83 |
84 | ngOnDestroy() {
85 | this.destroy$.next();
86 | }
87 |
88 | loadAndRenderRoute(route: Route) {
89 | if (route.loadComponent) {
90 | return route.loadComponent().then(component => {
91 | return this.renderView(component, this.outlet.nativeElement);
92 | });
93 | } else {
94 | return of(this.renderView(route.component, this.outlet.nativeElement));
95 | }
96 | }
97 |
98 | renderView(component: Type, host: any) {
99 | const cmpInjector = createInjector({}, this.injector, [
100 | { provide: RouteParams, useValue: this.routeParams$ }
101 | ]);
102 |
103 | this.rendered = renderComponent(component, {
104 | host,
105 | injector: cmpInjector
106 | });
107 |
108 | return this.rendered;
109 | }
110 |
111 | clearView() {
112 | this.outlet.nativeElement.innerHTML = "";
113 | this.rendered = null;
114 |
115 | return this.rendered;
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/projects/router/src/lib/router.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, SkipSelf, Optional } from "@angular/core";
2 | import { Location } from "@angular/common";
3 |
4 | import { combineLatest, Subject, BehaviorSubject } from "rxjs";
5 | import {
6 | tap,
7 | takeUntil,
8 | distinctUntilChanged,
9 | scan,
10 | debounceTime
11 | } from "rxjs/operators";
12 |
13 | import { pathToRegexp, match } from "path-to-regexp";
14 |
15 | import { Route, ActiveRoute } from './route';
16 | import { Router } from "./router.service";
17 | import { Params } from "./route-params.service";
18 |
19 | @Component({
20 | selector: "router",
21 | template: `
22 |
23 | `
24 | })
25 | export class RouterComponent {
26 | private destroy$ = new Subject();
27 | private _activeRoute$ = new BehaviorSubject(null);
28 | activeRoute$ = this._activeRoute$.pipe(distinctUntilChanged());
29 |
30 | private _routes$ = new BehaviorSubject([]);
31 | routes$ = this._routes$.pipe(
32 | scan((routes, route) => {
33 | routes = routes.concat(route);
34 |
35 | return routes;
36 | })
37 | );
38 |
39 | public basePath = "";
40 |
41 | // support multiple "routers"
42 | // router (base /)
43 | // blog(.*?)
44 | // router (base /blog)
45 | // post1(blog/post1/(.*?)
46 | // post2
47 | // post3
48 |
49 | constructor(
50 | private router: Router,
51 | private location: Location,
52 | @SkipSelf() @Optional() public parentRouterComponent: RouterComponent
53 | ) { }
54 |
55 | ngOnInit() {
56 | combineLatest(this.routes$.pipe(debounceTime(1)), this.router.url$)
57 | .pipe(
58 | takeUntil(this.destroy$),
59 | distinctUntilChanged(),
60 | tap(([routes, url]: [Route[], string]) => {
61 | let routeToRender = null;
62 | for (const route of routes) {
63 | routeToRender = this.findRouteMatch(route, url);
64 |
65 | if (routeToRender) {
66 | this.setRoute(url, route, routeToRender);
67 | break;
68 | }
69 | }
70 |
71 | if (!routeToRender) {
72 | this.setActiveRoute({ route: null, params: {} });
73 | }
74 | })
75 | )
76 | .subscribe();
77 | }
78 |
79 | findRouteMatch(route: Route, url: string) {
80 | let matchedRoute = route.matcher ? route.matcher.exec(url) : null;
81 |
82 | if (matchedRoute) {
83 | return matchedRoute;
84 | }
85 |
86 | // check to see if a greedy match will find something
87 | const secondaryMatch = pathToRegexp(`${route.path}(.*)`);
88 | const secondaryMatchedRoute = secondaryMatch.exec(url);
89 |
90 | if (secondaryMatchedRoute) {
91 | return secondaryMatchedRoute;
92 | }
93 | }
94 |
95 | setRoute(url: string, route: Route, matchedRoute: RegExpExecArray) {
96 | const useRoute = matchedRoute;
97 | const pathInfo = match(route.path)(url);
98 | this.basePath = useRoute[0] || "/";
99 |
100 | const routeParams: Params = pathInfo ? pathInfo.params : {};
101 | this.setActiveRoute({ route, params: routeParams || {} });
102 | }
103 |
104 | registerRoute(route: Route) {
105 | const normalizedPath = this.location.normalize(route.path);
106 | const routeRegex = pathToRegexp(normalizedPath);
107 | route.matcher = route.matcher || routeRegex;
108 | this._routes$.next([route]);
109 | return route;
110 | }
111 |
112 | setActiveRoute(active: ActiveRoute) {
113 | this._activeRoute$.next(active);
114 | }
115 |
116 | ngOnDestroy() {
117 | this.destroy$.next();
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "ngconf2020-reactive-router": {
7 | "projectType": "application",
8 | "schematics": {},
9 | "root": "",
10 | "sourceRoot": "src",
11 | "prefix": "app",
12 | "architect": {
13 | "build": {
14 | "builder": "@angular-devkit/build-angular:browser",
15 | "options": {
16 | "outputPath": "dist/ngconf2020-reactive-router",
17 | "index": "src/index.html",
18 | "main": "src/main.ts",
19 | "polyfills": "src/polyfills.ts",
20 | "tsConfig": "tsconfig.app.json",
21 | "aot": true,
22 | "assets": [
23 | "src/favicon.ico",
24 | "src/assets"
25 | ],
26 | "styles": [
27 | "src/styles.css"
28 | ],
29 | "scripts": []
30 | },
31 | "configurations": {
32 | "production": {
33 | "fileReplacements": [
34 | {
35 | "replace": "src/environments/environment.ts",
36 | "with": "src/environments/environment.prod.ts"
37 | }
38 | ],
39 | "optimization": true,
40 | "outputHashing": "all",
41 | "sourceMap": false,
42 | "extractCss": true,
43 | "namedChunks": false,
44 | "extractLicenses": true,
45 | "vendorChunk": false,
46 | "buildOptimizer": true,
47 | "budgets": [
48 | {
49 | "type": "initial",
50 | "maximumWarning": "2mb",
51 | "maximumError": "5mb"
52 | },
53 | {
54 | "type": "anyComponentStyle",
55 | "maximumWarning": "6kb",
56 | "maximumError": "10kb"
57 | }
58 | ]
59 | }
60 | }
61 | },
62 | "serve": {
63 | "builder": "@angular-devkit/build-angular:dev-server",
64 | "options": {
65 | "browserTarget": "ngconf2020-reactive-router:build"
66 | },
67 | "configurations": {
68 | "production": {
69 | "browserTarget": "ngconf2020-reactive-router:build:production"
70 | }
71 | }
72 | },
73 | "extract-i18n": {
74 | "builder": "@angular-devkit/build-angular:extract-i18n",
75 | "options": {
76 | "browserTarget": "ngconf2020-reactive-router:build"
77 | }
78 | },
79 | "test": {
80 | "builder": "@angular-devkit/build-angular:karma",
81 | "options": {
82 | "main": "src/test.ts",
83 | "polyfills": "src/polyfills.ts",
84 | "tsConfig": "tsconfig.spec.json",
85 | "karmaConfig": "karma.conf.js",
86 | "assets": [
87 | "src/favicon.ico",
88 | "src/assets"
89 | ],
90 | "styles": [
91 | "src/styles.css"
92 | ],
93 | "scripts": []
94 | }
95 | },
96 | "lint": {
97 | "builder": "@angular-devkit/build-angular:tslint",
98 | "options": {
99 | "tsConfig": [
100 | "tsconfig.app.json",
101 | "tsconfig.spec.json",
102 | "e2e/tsconfig.json"
103 | ],
104 | "exclude": [
105 | "**/node_modules/**"
106 | ]
107 | }
108 | },
109 | "e2e": {
110 | "builder": "@angular-devkit/build-angular:protractor",
111 | "options": {
112 | "protractorConfig": "e2e/protractor.conf.js",
113 | "devServerTarget": "ngconf2020-reactive-router:serve"
114 | },
115 | "configurations": {
116 | "production": {
117 | "devServerTarget": "ngconf2020-reactive-router:serve:production"
118 | }
119 | }
120 | }
121 | }
122 | },
123 | "router": {
124 | "projectType": "library",
125 | "root": "projects/router",
126 | "sourceRoot": "projects/router/src",
127 | "prefix": "lib",
128 | "architect": {
129 | "build": {
130 | "builder": "@angular-devkit/build-ng-packagr:build",
131 | "options": {
132 | "tsConfig": "projects/router/tsconfig.lib.json",
133 | "project": "projects/router/ng-package.json"
134 | },
135 | "configurations": {
136 | "production": {
137 | "tsConfig": "projects/router/tsconfig.lib.prod.json"
138 | }
139 | }
140 | },
141 | "test": {
142 | "builder": "@angular-devkit/build-angular:karma",
143 | "options": {
144 | "main": "projects/router/src/test.ts",
145 | "tsConfig": "projects/router/tsconfig.spec.json",
146 | "karmaConfig": "projects/router/karma.conf.js"
147 | }
148 | },
149 | "lint": {
150 | "builder": "@angular-devkit/build-angular:tslint",
151 | "options": {
152 | "tsConfig": [
153 | "projects/router/tsconfig.lib.json",
154 | "projects/router/tsconfig.spec.json"
155 | ],
156 | "exclude": [
157 | "**/node_modules/**"
158 | ]
159 | }
160 | }
161 | }
162 | }},
163 | "defaultProject": "router"
164 | }
165 |
--------------------------------------------------------------------------------