Reputation: 660
I have implemented state management using ngrx/store (Version 5.2.0) in angular (Version 5.2.9) application and with a typescript version(2.5.3).
I was having issue when i try to select the store and subscribe to it.
error TS2345: Argument of type '"appStateData"' is not assignable to parameter of type '"appState"'.
app.module.ts
import { StoreModule } from '@ngrx/store';
import { appReducer } from "./store/app.reducers";
...
imports: [
BrowserModule,
FormsModule,
...
StoreModule.forRoot({ appStateData: appReducer }),
],
reducer
import * as AppActions from "./app.actions";
export interface AppState {
appState: State;
}
export interface State {
values: [
{
modalStatus: boolean;
searchString: string;
chemString: string;
}
];
}
const intialState: State = {
values: [
{
modalStatus: false,
searchString: null,
chemString: null
}
]
};
export function appReducer(state = intialState, action) {
switch cases for all actions
...
}
my component and subscribe to store
import { Component, OnInit } from "@angular/core";
import { Store } from "@ngrx/store";
import * as fromAppReducer from "../store/app.reducers";
export class ResultComponent implements OnInit {
constructor(public store: Store<fromAppReducer.AppState>) {}
ngOnInit() {
this.store.select('appStateData').subscribe(data => {
this.searchString = data.values.slice(-1)[0].searchString;
});
}
}
Upvotes: 0
Views: 5090
Reputation: 3612
Your problem comes from this:
export interface AppState {
appState: State;
}
and this:
constructor(public store: Store<fromAppReducer.AppState>) {}
In your constructor, you're telling the component that the provisioned store has slices of state that align with the interface AppState
. The interface AppState
has one member, also named appState
. The Typescript compiler is helping you by saying you can only select a slice of state that exists -- in this case, that's a string "type" called appState
.
As a result, you need to change this:
this.store.select('appStateData')
to this:
this.store.select('appState')
Then subscribe and get the values out.
A better option in general would be to use selectors, which are detailed here:
https://github.com/ngrx/platform/blob/master/docs/store/selectors.md
Upvotes: 1