Giter Club home page Giter Club logo

ngrx-router's Introduction

NGRX Router

Router bindings for NGRX Effects. It allows you to bind to route activation to fetch data along with some common route actions such as go, back, foward.

This is different from ngrx-router-store in the fact this doesn't actually add anything to your store, it just emits events.

For more information, checkout this blog post.

Getting Started

To get started, lets install the package thru npm:

npm i ngrx-router --S

then include the effect in your module:

import { RouterEffects } from 'ngrx-router';

@NgModule({
    imports: [
        EffectsModule.forRoot([
            ...effects, // < Your other effects
            RouterEffects
        ]),
    ]
})
export class MyModule {}

Bindings

In an effect, you can do bind to route activations like:

import { ofRoute, mapToParam, RouteNavigation } from 'ngrx-router';

@Injectable()
export class MyEffect {
    constructor(private update$: Actions) {}

    @Effect()
    navigate$ = this.update$.pipe(
        ofRoute('pizza/:id'),
        mapToParam<string>('id'),
        map(id => new LoadPizza(id))
    );
}

The operator ofRoute supports the following syntax:

  • a simple match against a string ofRoute('pizza/:id')
  • a match against an array of strings ofRoute(['pizza/:id', 'burger/:id', 'burgers'])
  • a match against a regular expression ofRoute(/pizza|burger/)

Actions

You can also do navigation events with this library.

this.store.dispatch(new RouterGo({ path: ['pizza'] }))
this.store.dispatch(new RouterBack())
this.store.dispatch(new RouterForward())

Data

The RouteNavigation event also contains data which is defined in the Routes:

RouterModule.forRoot([
  {
    path: 'example',
    component: DummyComponent,
    data: { message: 'hello' },
  }
])
mapToData<string>('message'),

To get data aggregated from parent routes use the configuration parameter paramsInheritanceStrategy:

RouterModule.forRoot(routes, { paramsInheritanceStrategy: 'always' });

ngrx-router's People

Contributors

amcdnl avatar dhhyi avatar johanneshoppe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

johanneshoppe

ngrx-router's Issues

Feature request: wildcard

This would be very handy. Something with a "contains"-rule (e.g. ofRoute('pizza*')) or maybe a regex, too? ๐Ÿ˜„

New 2.0.0 package is broken - Cannot find module 'ngrx-router'.

Hi @amcdnl

I updated my project to NG6 and also tried to update ngrx-router from 1.0.0 to 2.0.0

  • with 1.0.0 my project compiles
  • with 2.0.0 i get the following error:
    ERROR in src/app/some.file.ts(0,00): error TS2307: Cannot find module 'ngrx-router'.
    

The angular package format must be somewhere broken. Without much investigation I would guess it is this line in package.json:

"main": "dist/index.js",

There is no index.js file in the dist folder of the final npm-package, so I wonder how this ever worked for you? ๐Ÿ˜• โ“

RouteNavigation is fired multiple times for nested routing

Hi,

when using the ngrx-router with nested routing (multiple <router-outlet>) the RouteNavigation action is fired multiple times. I think it should only fire once when the routing is concluded.

test case:

import { Component, Injectable } from '@angular/core';
import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { Actions, Effect, EffectsModule, ofType } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { ROUTER_NAVIGATION_TYPE, RouterEffects } from 'ngrx-router';
import { tap } from 'rxjs/operators';

@Injectable()
class DebugEffects {
  count = 0;
  constructor(private actions$: Actions) {}
  @Effect({ dispatch: false })
  countRouteEvents$ = this.actions$.pipe(
    ofType(ROUTER_NAVIGATION_TYPE), 
    tap(console.log), 
    tap(() => this.count++)
  );
}

describe('Ngrx Router Integration', () => {
  let router: Router;
  let debugEffects: DebugEffects;

  beforeEach(() => {
    @Component({ template: 'dummy' })
    class DummyComponent {}

    TestBed.configureTestingModule({
      declarations: [DummyComponent],
      imports: [
        StoreModule.forRoot({}),
        EffectsModule.forRoot([DebugEffects, RouterEffects]),
        RouterTestingModule.withRoutes([
          {
            path: 'a',
            component: DummyComponent,
            children: [{ path: 'b', component: DummyComponent }],
          },
        ]),
      ],
    });
    router = TestBed.get(Router);
    debugEffects = TestBed.get(DebugEffects);
  });

  it('fires twice on /a/b', fakeAsync(() => {
    router.navigate(['/a/b']);
    tick(1000);

    expect(debugEffects.count).toBe(2);
  }));
});

correspondig log output:

  console.log node_modules/rxjs/internal/operators/tap.js:103
    RouteNavigation {
      payload: { params: {}, queryParams: {}, path: 'a' },
      type: '[Router] Navigation' }


  console.log node_modules/rxjs/internal/operators/tap.js:103
    RouteNavigation {
      payload: { params: {}, queryParams: {}, path: 'a/b' },
      type: '[Router] Navigation' }


PASS src/app/core/store/routing-data/ngrx-router.integration.spec.ts

  Ngrx Router Integration
    โœ“ fires twice on /a/b (47ms)

Publish latest changes.

Hey,
would you mind publishing the latest changes to npm?
Some of the operators mentioned in the readme don't seem to be available when installing via npm.
ty :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.