Arash
Arash

Reputation: 12465

ngrx type of store when using feature module

As I understand, if I am to use feature modules, I create a state slice for each feature:

StoreModule.forFeature('user', userReducer.reducer)

And in the root module I do an

StoreModule.forRoot({})

Now when I want to use the store in my component I do is inject the store:

constructor( private store: Store<any>)

and

this.store.select(state => state.user.saveError) .subscribe((error) => { this.toastOptions.msg = error; this.toastyService.error(this.toastOptions); });

If all that is correct, what is the proper type of the store variable here?

Upvotes: 1

Views: 700

Answers (1)

Aleš Doganoc
Aleš Doganoc

Reputation: 12062

There is no specific type since the store is untyped but you can define interfaces to make it typed for development. What for StoreModule.forFeature('user', userReducer.reducer) does is it adds a property user in the root state that will hold the feature state. The Store you inject always contains all the state for the whole application that is why you have to use selectors. There are two possibilities how you could go about typing the store.

The first is to just focus on what you see inside the feature module and ignore the rest. Then it is similar to what is suggested in the comments. For example if you defined a state for your feature that is created by the userReducer:

export interface UserState {
  saveError: string;
}

Then the because you named the feature user the type for the store can be defined as:

export interface ApplicationState {
  user: UserState;
}

The second option if you know all the features in advance you can define an interface for all the structure of the store.

For example you have another feature with a different state:

export interface AnotherFeatureState {
  stateProperty: string;
}

Then the application state will be:

export interface ApplicationState {
  user?: UserState;
  anotherFature?: AnotherFeatureState;
}

I made the state properties optional because the modules can be lazy loaded an in such a case the properties do not exists until the modules are loaded. If you don't do lazy loading you can assume they are always there.

In both cases how you type in the constructor is:

constructor(private store: Store<ApplicationState>)

Upvotes: 0

Related Questions