router5
  • Read Me
  • Introduction
    • Why router5?
    • Getting Started
    • Ecosystem
    • Core concepts
    • Transition phase
  • Guides
    • Defining routes
    • Path Syntax
    • Router options
    • Navigating
    • In the browser
    • Observing state
  • Integration
    • With React
    • With Redux
  • Advanced
    • Plugins
    • Middleware
    • Preventing navigation
    • Errors and redirections
    • Dependency injection
    • Loading async data
    • Universal routing
    • Listeners plugin
  • API Reference
  • Migration
    • Migrating from 7.x to 8.x
    • Migrating from 6.x to 7.x
    • Migrating from 5.x to 6.x
    • Migrating from 4.x to 5.x
    • Migrating from 3.x to 4.x
    • Migrating from 2.x to 3.x
    • Migrating from 1.x to 2.x
    • Migrating from 0.x to 1.x
Powered by GitBook
On this page
  1. Advanced

Dependency injection

When using lifecycle methods (canActivate, canDeactivate), middleware or plugins, you might need to access specific objects from your application: a store, a specific API, etc... You can pass their reference to router5 and they will be passed alongside your router instance.

For TypeScript users, createRouter accepts a generic for typing dependencies.

You can register all dependencies at once, or one by one.

const router = createRouter(routes, options, dependencies)
router.setDependencies({ store, api })
// or
router.setDependency('store', store)
router.setDependency('api', api)

You can retrieve your current dependencies references using getDependencies().

Lifecycle methods (canActivate, canDeactivate), middleware or plugins will be called with them:

const plugin = (router, dependencies) => ({
    /*
        onStart() {},
        onStop() {},
        onTransitionStart() {},
        ...
    */
})
const canActivate = (router, dependencies) =>
    (toState, fromState, done) {
        /* ... */
    }
const middleware = (router, dependencies) =>
    (toState, fromState, done) {
        /* ... */
    }
PreviousErrors and redirectionsNextLoading async data

Last updated 5 years ago