Reputation: 847
I have an Angular 5 application that comprises several feature modules. Each module is responsible for assets of specific page and is lazy loaded.
src/
|--app/
|--core/ <-- core functionality here
|--landing/
|--store/
|--about-us/
For each module I have top level page component that connects to the store and fetch the data in very similar way across pages.
landing.component.ts
this.store.pipe(select(getDataForThisPage));
...
this.store.dispatch(new PageAction.FetchData());
So every page component fetches data from backend and places it into own feature store.
The problem here is that a) actions, b) effects and even reducer store shape are very similar for all feature modules. So ideally I want to reuse at least actions but if it's possible effects/store too.
What is the best way to do it?
Upvotes: 0
Views: 1774
Reputation: 57046
For actions, I guess you could use inheritance of some kind to extend actions with a payload.
More useful for you, in RxJs you can create custom operators to functionalise common operations. For example:
import { tap } from 'rxjs/operators'
import { Observable } from 'rxjs'
export const customLog = <T>(debug) => {
return (source: Observable<T>) => source.pipe(
tap((value) => { debug(value) })
)
}
And you can use this custom operator like so:
@Effect()
appInit$ = this.actions$.pipe(
ofType<InitAction>(InitActionTypes.Init),
customLog(debug),
// etc
)
Obviously, the logic in the custom filter pipe could be a lot more complex.
Upvotes: 0
Reputation: 1734
Have a look at @ngrx/entity.
If you want to do something like that yourself you can for example define an interface which defines how you store your data in your state. You can use a generic parameter to have type safety for the actual "entities". You can create helper functions that take an entity name as input and then create actions and a reducer, where as the actions are prefixed with your entity names.
But before trying it yourself I would give @ngrx/entity a go, just so you can get an idea on what is possible.
Upvotes: 1