In angular (v5) how do I listen to my apps Redux state object changing?

你说的曾经没有我的故事 提交于 2019-12-01 12:13:58

angular-redux offers a very convenient way of selecting slices of your store with the @select() decorator.

Let's say your IAppState would be:

export interface IAppState {
  counter: number;
  auth: {token: string}; 
}

Then you can select the parts of your state like this:

// variable name is equal to state property + $
@select() counter$: Observable<number>;
@select() auth$: Observable<{token: string}>;

// path to store slice
@select(['auth', 'token']) token$: Observable<string>;

For further information, have a look at the select docs.

I declare the actions in a file

// action.ts 
export const FILTER_ROLES = "FILTER_ROLES"

// this action will be handled in the effect
export class FilterRoles implements Action {
  readonly type = FILTER_ROLES
  constructor(public query: any) { }
}

export const FILTERED_ROLES = "FILTERED_ROLES"

// this one will modify the reducer 
export class FilteredRoles implements Action {
  readonly type = FILTERED_ROLES
  constructor(public values: Array<any>, public total: number) { }
}

the effects file will look like this, (effects will call the backend)

@Injectable()
export class RoleEffects {
@Effect() filter_roles = this.actions$
        .ofType(FILTER_ROLES)
        .flatMap((action: FilterRoles) => {
            return
                backendCall() 
                .mergeMap(({ values, total }) => {
                    return [
                        new FilteredRoles(values, total)
                    ]
                }).catch((err: Error) => { console.log("sss") })
}

the reducer will modify the current state of your store

export function RoleReducer(state: Roles = { values: [], total: 0 }, action: RoleActions) {

    switch (action.type) {
        case FILTERED_ROLES:
            return Object.assign({}, state, { values: action.values, total: action.total })
        default:
            return state
    }
}

In my module declaration you should declare both effects and reducer actions

const EffectModules = [
    EffectsModule.run(RoleEffects)
....
....
]

in the imports of my module I will declare all the reducer and effects

@NgModule({
    imports: [
StoreModule.provideStore({roles: RoleReducer,
... // all the other reducers
}),
...EffectModules,
]
})

I hope this code will help you

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!