1
votes

I have an Angular 4 app using ngrx. The current principal is part of the store. Whenever the principal changes (usually login or logout, but there might later be some sort of "switch user" functionality), I'd like to update the look&feel of the application. I already have code which will add a global CSS style, as well as replace a logo.

The part I'm unsure about: should this be implemented as ngrx effect, as a service, or something else?

store.select( 'principal' ).subscribe(( state ) => {
    this.updateCorporateIdentity( state );
} );

I currently have this in a CorporateIdentityService, but I'm not happy about the fact that I need to inject the service somewhere to get it created. Injecting it in app.component results in a lint error

Property 'corporateIdentityService' is declared but never used.

which I believe is justified. Another programmer will stumble upon that unused service and remove it. Ngrx effects, afaik, react to an action and produce a new action. My code won't produce a new action.

What's "the Angular way" to implement this?

Thanks

1
Effects are meant to perform some logic after an action has been dispatched.So I would do this within an effect. By having it within an effect, it is very clear that once action X is dispatched, logic Y is executed. - LLai
If you are putting the state of the view in ngrx then I'd suggest putting your logic in an effect that will update the view via ngrx. If that doesn't fit (not sure what you are changing) then you could use APP_INITIALIZER to bootstrap your service instead of injecting it into your app.component. - bygrace

1 Answers

0
votes

Thanks for the comments, I'll go with a ngrx effect:

export class PrincipalEffects {

    @Effect()
    updateCorporateIdentityOnPrincipalChange$: Observable<Action> = this.actions$
        .ofType( PrincipalActions.SET_PRINCIPAL )
        .flatMap(( action: ActionWithPayload<Principal> ) => {
            return this.corporateIdentityService.updateCorporateIdentity( action.payload );
        } )
        .map(( accountCode: string ) => this.principalActions.corporateIdentityUpdated( accountCode ) );

    constructor(
        private actions$: Actions,
        private corporateIdentityService: CorporateIdentityService,
        private principalActions: PrincipalActions ) { }

}