首页 > 解决方案 > 组件上未检测到 NGXS 更新状态

问题描述

我正在使用 NGXS 进行状态管理。它最初加载状态并且我已经可以看到应用程序,但是当我在撤回应用程序时尝试更新状态时,在组件上未检测到新状态。

还有一个问题,获取父组件的状态然后将其传递给子组件是否更好?或者我应该获取子组件的状态并在那里过滤所需的数据?

applications.state.ts

@State<Application[]>({
    name: `applications`,
    defaults: [],
})

export class ApplicationsState {
    constructor(private http: HttpClient) {}

    ngxsOnInit(context: StateContext<Applicationp[]> {
        context.dispatch(new GetApplications());
    }
    
    @Action(GetApplications)
    getApplications(context: StateContext<Application[]>) {
        return this.http.get<Application[]>(`...`).pipe(
            tap(resp => {
                context.setState(resp);
            })
        )
    }

    @Selector()
    static getApplications(state: Application[]) {
        return state;
    }

    @Action(WithdrawApplication)
    withdrawApplication(context: StateContext<Application[]>, { payload }: WithdrawApplication) {
        return this.http.put(`...`).pipe(
            tap(() => {
                ...
                ...
                context.setState(applications);
            })
        )
    }
}

父组件

applications.component.ts

@Select(ApplicationsState.getApplications) applications$: Observable<Application[]>;

applications.component.html
<application-card *ngFor="let application of applications$ | async" [application]="application" [filter]="filter"></application-card>

子组件

@Input() application: any;
...
...
...
 onWithdrawApplication() {
    this.store.dispatch(new WithdrawApplication(this.application));
  }

标签: angularstate-managementngxs

解决方案


推荐阅读