From 0e5d209f2eb55ab2784ab1fbc12b00c4acafb5bf Mon Sep 17 00:00:00 2001 From: Benjamin Cabanes Date: Thu, 8 Feb 2018 23:14:45 -0500 Subject: [PATCH] docs(Effects): Add example on initializing effects (#749) --- docs/effects/README.md | 1 + docs/effects/api.md | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/docs/effects/README.md b/docs/effects/README.md index e259f9d115..8d545417a1 100644 --- a/docs/effects/README.md +++ b/docs/effects/README.md @@ -103,5 +103,6 @@ export class AdminModule {} - [Controlling Effects](./api.md#controlling-effects) - [Filtering Actions](./api.md#oftype) - [Non-dispatching effects](./api.md#non-dispatching-effects) +- [Initializing effect](./api.md#initializing-effect) - [Utilities](./api.md#utilities) - [Testing](./testing.md) diff --git a/docs/effects/api.md b/docs/effects/api.md index da692a0910..2da070bf34 100644 --- a/docs/effects/api.md +++ b/docs/effects/api.md @@ -93,6 +93,47 @@ export class SomeEffectsClass { } ``` +### Initializing effect +You can execute some code that will be executed directly after the effect class is loaded. +```ts +import { Injectable } from '@angular/core'; +import { Actions, Effect, ofType } from '@ngrx/effects'; +import { defer } from 'rxjs/observable/defer'; +import { tap } from 'rxjs/operators'; + +@Injectable() +export class SomeEffectsClass { + constructor(private actions$: Actions) { } + + @Effect({ dispatch: false }) init$: Observable = defer(() => of(null)).pipe( + tap(() => console.log('init$')), + ); +} +``` + +If you want to trigger another action, be careful to add this effect at the end. +```ts +import { Injectable } from '@angular/core'; +import { Actions, Effect, ofType } from '@ngrx/effects'; +import { defer } from 'rxjs/observable/defer'; +import { LoginAction, LogoutAction } from './auth'; + +@Injectable() +export class SomeEffectsClass { + constructor(private actions$: Actions) { } + + @Effect({ dispatch: false }) authActions$ = this.action$.pipe( + ofType('LOGIN', 'LOGOUT'), + tap(action => console.log(action)) + ); + + // Should be your last effect + @Effect() init$: Observable = defer(() => { + return of(new LogoutAction()); + }); +} +``` + ## Controlling Effects ### OnRunEffects