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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With