Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right approach to display success, error messages via NGRX

I know two solutions for this problem, first one is to keep message in your state which doesn't seem good, second one is to subscribe to an ActionSubject which I currently use to display messages.

Is there any other solution for this ? Also how to set a CSS class in template, not in component ?

Here is my example:

 this.actionSubject.subscribe(action => {
      if (action.type === fromActions.LOGIN_SUCCESS) {
        this.message$ = action.payload.message;
        this.messageClass = 'alert alert-success';
      }
      if (action.type === fromActions.LOGIN_FAILURE) {
        this.message$ = action.payload.error.message;
        this.messageClass = 'alert alert-danger';
        this.LoginForm.reset();
      }
    })

It seems too long, not DRY, I should do this in every component where I expect to have a message.

like image 967
merko Avatar asked Feb 18 '18 18:02

merko


People also ask

When we should and when we should not use NgRx?

When should you not use NgRx? Never use NgRx if your application is a small one with just a couple of domains or if you want to deliver something quickly. It comes with a lot of boilerplate code, so in some scenarios it will make your coding more difficult.


1 Answers

Example from original docks https://github.com/ngrx/effects/blob/master/docs/intro.md

Create an AuthEffects service that describes a source of login actions:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Actions, Effect } from '@ngrx/effects';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AuthEffects {
  constructor(
    private http: Http,
    private actions$: Actions
  ) { }

  @Effect() login$ = this.actions$
      // Listen for the 'LOGIN' action
      .ofType('LOGIN')
      // Map the payload into JSON to use as the request body
      .map(action => JSON.stringify(action.payload))
      .switchMap(payload => this.http.post('/auth', payload)
        // If successful, dispatch success action with result
        .map(res => ({ type: 'LOGIN_SUCCESS', payload: res.json() }))
        // If request fails, dispatch failed action
        .catch(() => Observable.of({ type: 'LOGIN_FAILED' }))
      );
}

Provide your service via EffectsModule.run to automatically start your effect:

import { EffectsModule } from '@ngrx/effects';
import { AuthEffects } from './effects/auth';

@NgModule({
  imports: [
    EffectsModule.run(AuthEffects)
  ]
})
export class AppModule { }

Note: For effects that depend on the application to be bootstrapped (i.e. effects that depend on the Router) use EffectsModule.runAfterBootstrap. Be aware that runAfterBootstrap will only work in the root module.

Else you can look about using guard with effect here: https://toddmotto.com/preloading-ngrx-store-route-guards

like image 61
Kliment Ru Avatar answered Oct 15 '22 14:10

Kliment Ru