【问题标题】:Using payload of action on ActionsSubject subscription on NGRX在 NGRX 上的 ActionsSubject 订阅上使用操作的有效负载
【发布时间】:2018-07-27 18:14:53
【问题描述】:

我得到了旧的和坏的Property 'payload' does not exist on type 'Action做这个动作订阅:

由于是创建操作,我需要有效负载来签出最近创建的用户的 userId 并导航到 /users/userId

顺便说一句:我正在关注this really nice tutorial

@Component({
  selector: 'app-sample',
  templateUrl: 'sample.html',
})
export class AppComponent {
  subs = new Subscription();

  constructor(private actionsSubject: ActionsSubject) {
    this.subs = actionsSubject.subscribe(action => {
      if (action.type === actions.CREATE_USER_SUCCESS) {
        console.log(action.payload);
      }
    });
  }
}

【问题讨论】:

    标签: angular observable ngrx ngrx-store ngrx-entity


    【解决方案1】:

    如果您查看 ActionsSubject 类声明,您会注意到,当您订阅它时,您应该获得 Action 类的对象,定义如下:

    export interface Action {
      type: string;
    }
    

    如您所见,这里根本没有payload。这意味着您需要告诉 TypeScript,如果您希望某个对象的类型更加严格。

    我会尝试(假设您的 Action 类名为 CreateUserSuccessAction):

    this.subs = actionsSubject.subscribe((action: Action) => {
      if (action.type === actions.CREATE_USER_SUCCESS) {
        let createUserAction: CreateUserSuccessAction = action as CreateUserSuccessAction;  
        console.log(action.payload);
      }
    });
    

    或更好(假设您使用 RxJS 6):

    this.subs = actionsSubject.pipe(
      filter((action: Action) => action.type === actions.CREATE_USER_SUCCESS)
    ).subscribe((action: CreateUserSuccessAction) => {
      console.log(action.payload);
    });
    

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 2018-01-06
      • 2020-08-02
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多