我如何从ngxs中的另一个组件获取状态值

时间:2020-08-21 01:06:46

标签: angular 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 }}

我无法获取superAdminState状态值,因为html值中的superAdminState显示未定义

superAdminState value is undefined

action changed the state value

1 个答案:

答案 0 :(得分:0)

您的布局组件的onClick方法很好,它将分派您需要设置状态的操作。所缺少的是,您还将要在此组件中使用选择器。 @Select(CommonState.superAdminState) superAdminState: Observable<any>;

相关问题