Search code examples
angularngxs

how can i get state value from another component in ngxs


common.state.ts

import { Action, Selector, State, StateContext } from '@ngxs/store';
import { NzMessageService } from 'ng-zorro-antd';
import { PermissionDict } from '../../model/organization-authority/setting/permission-dict.model';
import { CommonService } from '../../service/common.service';
import {GetIsSuperAdminAction} from '../action/common.action';
import { map } from 'rxjs/operators';
import { Injectable } from '@angular/core';

export interface CommonStateModel {
   superAdminState: number;
}

@State<CommonStateModel>({
    name: '_CommonState',
    defaults: {
        superAdminState: null
    }
})
@Injectable()
export class CommonState {
constructor(
    private _commonService: CommonService,
  
) {}

@Selector()
public static superAdminState(state: CommonStateModel) {
    console.log(state.superAdminState + 'A');
   //is not execute
    return state.superAdminState;
}



/**
 * @param ctx
 * @param action
 */
@Action(GetIsSuperAdminAction)
GetIsSuperAdminAction(ctx: StateContext<CommonStateModel>, action: GetIsSuperAdminAction) {
    console.log(action.superAdminState);
    const state = ctx.getState();
    ctx.setState({ ...state, superAdminState: action.superAdminState });
}

}

layout.component.ts:

onClick(){
   this._store.dispatch(new GetIsSuperAdminAction(Math.random()));
}

worker-dashboard.component.ts

superAdminState: Observable<number>;
this.superAdminState = this._store.select(CommonState.superAdminState);

worker-dashboard.component.html

{{ superAdminState | async }}

i can't get superAdminState state value,because superAdminState display in html value is undefined

superAdminState value is undefined

action changed the state value


Solution

  • Your layout component onClick method is fine and will dispatch the action you need to set the state. The thing that is missing is you will want to use the selector in this component as well. @Select(CommonState.superAdminState) superAdminState: Observable<any>;.