Home > OS >  How to avoid god components in Angular?
How to avoid god components in Angular?

Time:02-14

I am experimenting with Angular. In classical fashion I have separated the template, styles and component into 3 different files.

The component file contains different functions.

  • Some are triggered by events (e.g. button clicks) from the template, some are not.
  • Some functions are async, some are not.
  • Some open modal dialogs, some don't.
  • Some execute file operations, others don't.
  • Some functions are high-level and return their result through the snackbar, others don't.

This tends to make component class become a god object, how can this be avoided? And also, how can I avoid the sheer mix of functions? I can export functions to other files, but that means that objects passed to the constructor of the component need to be forwarded which doesn't look like the way to go:

import { doSomething } './helper';

[...]

class Foo Component {
    doSomething(this.snackBar,  <-- smelly code
                     "X", 1, 2, 3)

CodePudding user response:

Don't hold the state of the components inside of the components, hold it in a state management library.

By doing this you don't need to pass this.snackBar because there is nothing to be done upon, no mutation of the actual component. Anything that should be done in doSomething can be done in the action that will be called.

Whether its rxjs, ngrx, ngxs (note the examples I'll use are ngxs) or whatever library of your choice.

So you'll have this type of code to execute button an action:

public doSomething(): void {
   this.store.dispatch(new DoSomeThingCommand("X", 1, 2, 3));
}

and to retrieve the actual state you can use reducers:

@Select(state => state.someState.isSomethingDone)
public isSomethingDone$: Observable<boolean>

So in this way the only mutation you are going to have is in the store, rather than the components thus avoiding any dependency on the actual components.

  • Related