首页 > 解决方案 > 在 Angular 10 和 RxJs 中调用了错误的动作类型或错误的减速器

问题描述

我在 Angular 10 应用程序中使用 RxJs 创建了两个状态。我面临的问题是错误的动作类型或错误的减速器被调用。

我已经在下图中解释了这个问题。

说明图

我不确定我应该提供代码的哪一部分。所以我只是提供我的行动。如果我需要提供其他代码,请告诉我。我是 RxJs 或 redux 的新手。我想我犯了基本错误。

绘制列表动作

import {Action} from '@ngrx/store'
import {Draw} from "../../../models/Draw";

export const GET_LIVE_DRAWS = '[GET_LIVE_DRAWS] Try get'
export const GET_LIVE_DRAWS_SUCCESS = '[GET_LIVE_DRAWS] Success'
export const GET_LIVE_DRAWS_FAIL = '[GET_LIVE_DRAWS] failure'



export class GetLiveDraws implements Action {
  readonly type = GET_LIVE_DRAWS

  constructor() {
  }
}

export class GetLiveDrawsSuccess implements Action {
  readonly type = GET_LIVE_DRAWS_SUCCESS

  constructor(data: Draw[]) {
  }
}

export class GetLiveDrawsFailure implements Action {
  readonly type = GET_LIVE_DRAWS_FAIL

  constructor(public data: any) {
  }
}


export type Actions = GetLiveDraws | GetLiveDrawsSuccess | GetLiveDrawsFailure

身份验证操作

import {Action} from '@ngrx/store'
import {User} from "../../../models/User";
import {Keys} from "../../../config/keys";

export const AUTHENTICATE = '[Auth] Try Login'
export const AUTHENTICATION_SUCCESS = '[Auth] Success'
export const AUTHENTICATION_FAIL = '[Auth] failure'

export const LOGOUT = '[Auth] Try LOGOUT'
export const LOGOUT_SUCCESS = '[Auth] LOGOUT Success'
export const LOGOUT_FAIL = '[Auth] LOGOUT failure'


export class Authenticate implements Action {
  readonly type = AUTHENTICATE

  constructor(public username: string, public password: string) {
  }
}

export class AuthenticationSuccess implements Action {
  readonly type = AUTHENTICATION_SUCCESS

  constructor(public data: User) {
    localStorage.setItem(Keys.USER_KEY, JSON.stringify(data))
    localStorage.setItem(Keys.ACCESS_TOKEN, data.access_token)
  }
}

export class AuthenticationFailure implements Action {
  readonly type = AUTHENTICATION_FAIL

  constructor(public data: any) {
    localStorage.removeItem(Keys.USER_KEY);
    localStorage.removeItem(Keys.ACCESS_TOKEN);
  }
}

/// Logout

export class Logout implements Action {
  readonly type = LOGOUT

  constructor(public id: number) {
  }
}

export class LogoutSuccess implements Action {
  readonly type = LOGOUT_SUCCESS

  constructor() {
    localStorage.removeItem(Keys.ACCESS_TOKEN);
    localStorage.removeItem(Keys.USER_KEY);
  }
}

export class LogoutFailure implements Action {
  readonly type = LOGOUT_FAIL

  constructor() {
    localStorage.removeItem(Keys.USER_KEY);
    localStorage.removeItem(Keys.ACCESS_TOKEN);
  }
}


export type Actions = Authenticate | AuthenticationSuccess | AuthenticationFailure |
  Logout | LogoutSuccess | LogoutFailure

标签: angularreduxrxjsngrxangular10

解决方案


从外观上看,您有一个动作正在被 2 个不同的减速器监听。请记住,一个动作是广播的,如果你设置它们,任何/所有减速器都可以监听它。如果您需要从 1 个操作的结果更新两个状态切片,这可能很有用,但它会使您的代码更复杂一些,并将状态的不同部分联系在一起


推荐阅读