I have reducer whith action which can create new property in state.
app.module.ts
import { appReducers } from './app.reducers';
NgModule( {
imports: [
//.... standart modules
StoreModule.forRoot( appReducers ),
app.reducers.ts
import * as fromGadgetReducer from './gadgets/gadget.reducer';
export interface State {
gadgets: fromGadgetReducer.State;
}
export const appReducers = {
gadgets: fromGadgetReducer.reducer,
};
gadget.reducer.ts
import * as gadgetActions from './gadget.actions';
export interface State {
dummy: any;
}
const initialState: State = {
dummy: ''
};
export function reducer( state = initialState, action: gadgetActions.AllTypes ): State {
switch ( action.type ) {
case gadgetActions.SET_PROPERTY:
const newState = { ...state };
newState[ action.propertyName ] = action.value;
return newState;
}
}
gadget.actions.ts
export const SET_PROPERTY = '[ Gadget ] Set property';
export class SetProperty implements Action {
readonly type = SET_PROPERTY;
constructor( public propertyName: string, public value: any ) {
}
}
export type AllTypes = SetProperty;
Now when i will call action from Angular5 component
this.store.dispatch( new SetProperty( 'newProp', 'value' ) );
state will looks like { dummy:'', newProp:'value' }.
My next step - subscribing to changes for that property. But here i have problem. When i subscribing from Angular 5 component, that property not exists in state.
@Component( {
//standart stuff
} )
export class GadgetComponent implements OnInit{
@Input() propName: string = ;
constructor( private store: Store<State>) {
}
ngOnInit(){
this.store.dispatch( new SetProperty( this.propName, '' ) );
this.store.select( state => state.gadgets[this.propName]).subscribe( value => {
// Problem: value === undefined
//do some action
});
}
}
My Question: How i can check existing property in store, create if not exists and subscribe to that property? I try next, but it is not working:
this.store.select( state => state.gadgets.newProp ).take( 1 )
.subscribe( state => {
if ( typeof state === 'undefined' ) {
// create property in state
this.store.dispatch( new SetProperty( 'newProp', '' ) );
}
this.store.select(state => state.gadgets.newProp).subscribe( value => {
// Problem: value === undefined
//do some action
});
} );