Angular with ngRx and experimental ngrx-data helper
Permalink
Failed to load latest commit information.
.github init Nov 26, 2017
.vscode init Nov 26, 2017
docs 6.1.0-beta.0 Oct 10, 2018
e2e refactor: cleaner toast Mar 15, 2018
lib fix: remove incorrect comment in Effects Oct 12, 2018
server breaking changes: update to Angular/RxJS/Ngrx v6 v6.0.0-beta.1 (#147) May 8, 2018
src 6.1.0-beta.0 Oct 10, 2018
.dockerignore init Nov 26, 2017
.editorconfig ran prettier Dec 10, 2017
.env.example changed server_port to PORT Dec 16, 2017
.gitignore refactor: entity reducers - Beta 8 (#133) Apr 15, 2018
.prettierignore Prettier precommit hook (#126) Mar 21, 2018
.prettierrc feat: 6.1.0-alpha.2 enhancements (#189) Sep 19, 2018
.snyk snyk Nov 29, 2017
CHANGELOG.md feat: extend sample app with saveEntities example Sep 19, 2018
CONTRIBUTING.md feat: add change tracking and much more (6.0.2-beta.7) (#162) Jun 27, 2018
Dockerfile build Dec 8, 2017
LICENSE.md init Nov 26, 2017
README.md 6.1.0-beta.0 Oct 10, 2018
angular.json breaking changes: update to Angular/RxJS/Ngrx v6 v6.0.0-beta.1 (#147) May 8, 2018
docker-compose.debug.yml docs: finish rename of angular-ngrx -> angular-ngrx-data Feb 1, 2018
docker-compose.yml docs: finish rename of angular-ngrx -> angular-ngrx-data Feb 1, 2018
karma.conf.js breaking changes: update to Angular/RxJS/Ngrx v6 v6.0.0-beta.1 (#147) May 8, 2018
package-lock.json feat: Save multiple entities to cache in single transaction - v7.0.0-… Sep 19, 2018
package.json feat: Save multiple entities to cache in single transaction - v7.0.0-… Sep 19, 2018
protractor.conf.js testing: add e2e tests for sample app Mar 15, 2018
proxy.conf.json init Nov 26, 2017
server.js breaking changes: update to Angular/RxJS/Ngrx v6 v6.0.0-beta.1 (#147) May 8, 2018
tsconfig.json breaking changes: update to Angular/RxJS/Ngrx v6 v6.0.0-beta.1 (#147) May 8, 2018
tslint.json breaking changes: update to Angular/RxJS/Ngrx v6 v6.0.0-beta.1 (#147) May 8, 2018
yarn.lock breaking changes: update to Angular/RxJS/Ngrx v6 v6.0.0-beta.1 (#147) May 8, 2018

README.md

Angular ngrx-data

prettier

Zero Ngrx Boilerplate

You may never write an action, reducer, selector, effect, or HTTP dataservice again.

NgRx helps Angular applications manage shared state in a "reactive" style, following the redux pattern.

But to use it properly requires both a deep understanding of redux/ngrx and a lot of boilerplate code.

Ngrx-data is an ngrx extension that offers a gentle introduction to ngrx/redux without the boilerplate.

Try it! See the Quick Start for instructions on adding NgRx and ngrx-data to your app.

Why use ngrx-data?

Many applications have substantial domain models with 10s or 100s of entity types such as Customer, Order, LineItem, Product, and User.

In plain ngrx, to create, retrieve, update, and delete (CRUD) data for every entity type is an overwhelming task. You're writing actions, action-creators, reducers, effects, dispatchers, and selectors as well as the HTTP GET, PUT, POST, and DELETE methods for each entity type.

In even a small model, this is a ton of repetitive code to create, maintain, and test.

The ngrx-data library is one way to stay on the ngrx path while radically reducing the "boilerplate" necessary to manage entities with ngrx.

It's still NgRx

This is a library for ngrx, not an ngrx alternative.

It's easy to combine standard ngrx with ngrx-data. It's easy to take control when you need it and hand control back to ngrx-data when you're done.

Every entity has its own actions. Every operation takes its unique journey through the store, reducers, effects, and selectors. You just let ngrx-data create these for you.

You can add custom store properties, actions, reducers, selectors, and effects. You can override any ngrx-data behavior for an individual entity type or for all entities. You can make your own calls to the server and update the cached entity collections with the results using ngrx-data cache-only actions.

You can see the ngrx machinery at work with the redux developer tools. You can listen to the flow of actions directly. You can intercept and override anything ... but you only have to intervene where you want to add custom logic.

Learn about it

For a hands-on experience, try the QuickStart in the tutorial git repo, ngrx-data-lab, which guides you on the few, simple steps necessary to migrate from a typical service-based Angular app, to an app that manages state with ngrx-data.

This ngrx-data repository has the main documentation and its own sample app.

The sample app in the src/client/app/ folder presents an editor for viewing and changing Heroes and Villains.

The following reduced extract from that demo illustrates the essential mechanics of configuring and using ngrx-data.

You begin with a description of the entity model in a few lines of metadata.

// Metadata for the entity model
export const entityMetadata: EntityMetadataMap = {
  Hero: {},
  Villain: {}
};

// Help ngrx-data pluralize entity type names
// because the plural of "Hero" is not "Heros"
export const pluralNames = {
  Hero: 'Heroes' // the plural of Hero
};

You register the metadata and plurals with the ngrx-data module.

@NgModule({
  imports: [
    NgrxDataModule.forRoot({
      entityMetadata: entityMetadata,
      pluralNames: pluralNames
    })
  ]
})
export class EntityStoreModule {}

Your component accesses each entity data through an EntityCollectionService which you can acquire from the ngrx_data EntityServices.

In the following example, the HeroesComponent injects EntityServices and asks it for an EntityCollectionService registered under the Hero entity name.

The component uses that service to read and save Hero entity data in a reactive, immutable style, without reference to any of the ngrx artifacts.

import { EntityCollectionService, EntityServices } from 'ngrx-data';
import { Hero } from '../../core';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HeroesComponent implements OnInit {
  heroes$: Observable<Hero[]>;
  heroesService: EntityCollectionService<Hero>;

  constructor(entityServices: EntityServices) {
    this.heroesService = entityServices.getEntityCollectionService('Hero');
    this.heroes$ = this.heroesService.entities$;
  }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes() {
    this.heroesService.getAll();
  }

  addHero(hero: Hero) {
    this.heroesService.add(hero);
  }

  deleteHero(hero: Hero) {
    this.heroesService.delete(hero.id);
  }

  updateHero(hero: Hero) {
    this.heroesService.update(hero);
  }
}

As you explore ngrx-data and its documentation, you'll learn many extension points and customizations that tailor the developer experience to your application needs.

QuickStart

Try the Quick Start to experience NgRx and ngrx-data in your app.

Explore this repository

This repository contains the ngrx-data source code and a demonstration application (the "demo app") that exercises many of the library features.

The key folders in this repository are:

  • docs --> the docs for the library and the demo
  • lib ---> the ngrx-data library source code that we publish to npm
  • src/app ---> the demo app source
  • server ---> a node server for remote data access

Learn more in the docs

Install and run

The demo app is based on the Angular CLI. You may want to install the CLI globally if you have not already done so.

npm install -g @angular/cli

Then follow these steps:

  1. Clone this repository

    git clone https://github.com/johnpapa/angular-ngrx-data.git
    cd angular-ngrx-data
  2. Install the npm packages

    npm install
  3. Build the ngrx-data library

    npm run build-setup
  4. Serve the CLI-based demo app

    ng serve -o

Refer to the troubleshooting section if you run into installation issues.

Run the library tests

The ngrx-data library ships with unit and E2E (end-to-end) tests to validate functionality and guard against regressions.

These tests also demonstrate features of the library that are not covered in the demo app. They're worth reading to discover more advanced techniques.

Run this CLI command to execute the unit tests for the library.

ng test

Run the sample app E2E (end-to-end) tests.

npm run e2e

We welcome PRs that add to the tests as well as those that fix bugs and documentation.

Be sure to run these tests before submitting a PR for review.

Monitor the app with Redux DevTools

The demo app is configured for monitoring with the Redux DevTools.

Follow these instructions to install them in your browser and learn how to use them.

Debug the library in browser dev tools

When running tests, open the browser dev tools, go to the "Sources" tab, and look for the library files by name.

In chrome, type [Command-P] and letters of the file name.

When running the app (e.g., with ng serve), the browser dev tools give you TWO choices for a given TypeScript source file, both claiming to be from .ts.

The one you want for library and app files ends in /lib/src/file-name.ts and /src/client/app/path/file-name.ts respectively.

Hope to solve the two file problem.

Build the app against the source

The demo app is setup to build and run against the ngPackagr artifacts in dist/ngrx-data, the same artifacts delivered in the npm package.

Re-build the library npm run build-lib or npm run build-setup or npm run build-all to update these artifacts.

This approach, while safe, can be inconvenient when you're evolving the library code because "Go to definition" takes you to the d.ts files in dist/ngrx-data rather than the source files in lib/src.

If you want to "Go to definition" to take you to the source files, make the following *temporary changes to the TypeScript configuration.

  1. Replace the paths target in the root tsconfig.json so that the IDE (e.g., VS Code) looks for ngrx-data in src/lib.

      "paths": {
        "ngrx-data": ["lib/src"]
      },
  2. Replace that same setting in the config at src/tsconfig.json.

  3. Replace that same setting in src/client/tsconfig.app.json. Now ng build references src/lib when it builds the demo app.

Remember to restore the tsconfig settings when you're done. Do not commit those changes!

Use a real database

The demo app queries and saves mock entity data to an in-memory database with the help of the Angular In-memory Web API.

The "Remote Data" toggle switch in the header switches to the remote database.

The app fails when you switch to the remote database.

Notice how the app detects errors and pops up a toast message with the failed ngrx Action.type.

The error details are in the browser's console log.

You must first set up a database and launch a web api server that talks to it.

The src/server folder has code for a local node web api server, configured for the demo app.

TODO: Explain how to build and run the server. Explain how to build and serve the mongo db

Bad/surplus npm scripts

We know there are a great many npm script commands in package.json, many (most?) of which don't work.

They're on our list for future cleanup. Please don't create issues for them (although PRs that fix them are welcome).

Troubleshooting

Installation

  1. If you are on Windows and run into this error during npm install: "snyk couldn't patch the specified vulnerabilities because gnu's patch is not available", refer to this issue for the fix. In short, your Git installation is not correct or C:\Program Files\Git\usr\bin (typically) is not added to your system environment variable %PATH%.

Problems or Suggestions

Open an issue here