0

我有减速器,它可以在状态下创建新属性。

app.module.ts

import { appReducers } from './app.reducers';

NgModule( {
    imports: [
    //.... standart modules
    StoreModule.forRoot( appReducers ),

应用程序.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;
    }
}

小工具.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;

现在当我从 Angular5 组件调用动作时

this.store.dispatch( new SetProperty( 'newProp', 'value' ) );

state 看起来像 { dummy:'', newProp:'value' }。

我的下一步 - 订阅该属性的更改。但在这里我有问题。当我从 Angular 5 组件订阅时,该属性在状态中不存在。

@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 
       });
    }
}

我的问题:我如何检查商店中的现有属性,如果不存在则创建并订阅该属性?我接下来尝试,但它不起作用:

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 
        });
     } );
4

0 回答 0