Skip to content

Route

Class for creating path based route.
Routes are self-contained entities and do not require binding to a router.

You can track their open state using theisOpenedproperty, and also "open" the route using theopen()method.

Constructor

ts
newRoute(path: TPath,config?:RouteConfiguration<TParentRoute>,)

Basic example

ts
constusers=newRoute('/users');users.open();constuserDetails=users.extend('/:userId');userDetails.open({ userId:1});constuserPhotos=userDetails.extend('/photos');userPhotos.open({ userId:1});userPhotos.isOpened;// true;location.pathname;// /users/1/photos

Route path

The route path is built using thepath-to-regexplibrary. The path itself is specified as the first parameter when creating an instance of theRouteclass.

So you can use all power of this library with TypeScript support out-of-box

ts
constroute=newRoute('/*segment');route.open({segment: [1,2,3]})

Methods and properties

open(...args)

Navigates to this route.
First argument can be required based on path declaration (first argument)

API Signature

ts
open(params?, { query?, replace?, state?, mergeQuery? }):Promise<void>open(params?, replace?, query?):Promise<void>

More aboutmergeQueryyou can readhere

Examples:

ts
conststars=newRoute('/stars');awaitstars.open();location.pathname;// /stars
ts
conststarDetails=newRoute('/stars/:starId');awaitstarDetails.open({ starId:1}, {query: { bar:'baz'}});conststarsWithMeta=newRoute('/stars{/:meta}');awaitstarsWithMeta.open();awaitstarsWithMeta.open({ meta:1}, {query: { foo:'bar'},});

extend(path, config): Route

Allows to create child route based on this route with merging this route path and extending path.
Example:

ts
conststars=newRoute('/stars');conststarDetails=stars.extends('/:starId');starDetails.path;// '/stars/:starId'awaitstarDetails.open({ starId:1});location.pathname;// /stars/1

isIndex: boolean

Indicates if this route is an index route. Index routes activate when parent route path matches exactly.
Useful with groupping routes usingRouteGroup

isHash: boolean

Indicates if this route is an hash based route.
Hash based routes work with only#hashstringsin browser address URL. This is useful when you want to create routes that only affect the hash part of the URL, such as for client-side routing or for creating routes that don't affect the server-side routing.

isOpened: booleancomputed.struct

Defines the "open" state for this route.
Returns true when current URL matches this route's path pattern.

Example:

ts
conststars=newRoute('/stars');stars.open();stars.isOpened;// true

params: ParsedPathParams | nullcomputed.struct

Current parsed path parameters.nullif route isn't open.

Example:

ts
constrouteA=newRoute('/foo/bar/:baz');location.href='/foo/bar/1234';routeA.params;// { baz: "1234" }

parent: TParentRoute | nullobservable.ref

Parent route

Example:

ts
constrouteA=newRoute('/a');constrouteB=routeA.extend('/b');routeB.parent===routeA;// true

currentPath: ParsedPathName | nullcomputed.struct

Matched path segment for current URL.nullif route isn't open.

Example:

ts
constrouteA=newRoute('/foo/bar/:baz');location.href='/foo/bar/1234';routeA.currentPath;// '/foo/bar/1234'

hasOpenedChildren: booleancomputed.struct

truewhen any child route is currently opened.

Example:

ts
constrouteA=newRoute('/a');constrouteB=routeA.extend('/b');constrouteC=routeB.extend('/c');history.pushState(null,'','/a/b/c');routeA.isOpened;// falserouteB.isOpened;// false;routeC.isOpened;// true;routeA.hasOpenedChildren;// truerouteB.hasOpenedChildren;// truerouteC.hasOpenedChildren;// false

children: AnyRoute[]observable

Array of child routes. Automatically updated when usingextend().

createUrl(params?, query?, mergeQuery?): string

Generates full URL for route. Respects base URL and parent routes.

Example:

ts
conststarDetails=newRoute('/stars/:starId');starDetails.createUrl({ starId:1}, { bar:1});// /stars/1?bar=1starDetails.createUrl({ starId:1}, { baz:2},true);// /stars/1?bar=1&baz=2

More aboutmergeQueryyou can readhere

path: string

Original path pattern used for route matching.

Example:

ts
conststarDetails=newRoute('/stars/:starId');starDetails.path;// /stars/:starId

addChildren(...routes: AnyRoute[]): voidaction

Manually add child routes. Preferextend()for typical use cases.

removeChildren(...routes: AnyRoute[]): voidaction

Remove specified routes from children.

Configuration

Interface:RouteConfiguration
This is specific object used to detailed configure route.
Here is list of configuration properties which can be helpful:

abortSignal

AbortSignalused to destroy\cleanup route subscriptions

meta

Additional object which can contains meta information

ts
constroute=createRoute('/fruits/apples', {meta: {memes:true}});console.log(route.meta?.memes);// true

params()

A function that can be needed when it is necessary to cast parsed path parameters from route to a certain type.

ts
constroute=createRoute('/fruits/apples/:appleId', {params: (params)=>{return{appleId: params.appleId,isIphone: params.appleId.includes('iphone')}}});route.open({ appleId:'iphone'})route.params?.isIphone;// true

Also it can block "opened" statement for route if you will returnfalseornullvalue from this function.

ts
constroute=createRoute('/numbers/:number', {params: (params)=>{if(Number.isNaN(Number(params.number))) {returnnull}return{number:Number(params.number)}}});route.open({ number:'string'})route.isOpened;// false

checkOpened()

Function allows you to add custom logic for "opened" statement

This check will only be called AFTER if this route is valid bypathname

ts
constroute=createRoute('/numbers/:number', {checkOpened: (params)=>{return!Number.isNaN(Number(params.number))}});route.open({ number:'string'})route.isOpened;// false

beforeOpen

Event handler "before opening" a route, required for various checks before the route itself is opened.
With this handler, we can prevent the route from opening by returningfalse,
or override the navigation to another one by returning

ts
{url: string;state?:any;replace?:boolean;}

Example:

ts
constroute=newRoute('/foo/bar', {beforeOpen: ()=>{if(!auth.isAuth) {returnfalse;}}})

afterClose()

Calls after close route.

afterOpen()

Calls after open route.

createUrl()

Ability to customize path or query params before create route url.

Example:

ts
constroute=newRoute('/foo/bar/baz',{createUrl: ({params,query})=>{return{params,query: {...query,openModal:true,}}}});route.createUrl();// /foo/bar/baz?openModal=trueroute.open();// /foo/bar/baz?openModal=true

Released under the MIT License.