在NGRX上的ActionsSubject订阅上使用操作的有效负载 [英] Using payload of action on ActionsSubject subscription on NGRX

查看:41
本文介绍了在NGRX上的ActionsSubject订阅上使用操作的有效负载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行此操作订阅时,类型'Action 上不存在旧的和错误的属性'payload':

I got the old and bad Property 'payload' does not exist on type 'Action doing this actions subscription:

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

Since is a Creation Action, I need the payload to checkout the userId of the recently created User and navigate to /users/userId

顺便说一句:我正在关注这真的很好的教程

BTW: I'm following 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);
      }
    });
  }
}

推荐答案

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

If you take a look at ActionsSubject class declaration, you will notice that when you subscribe to it, you are supposed to get objects of class Action, defined like so:

export interface Action {
  type: string;
}

如您所见,这里根本没有 payload .这意味着您需要告诉TypeScript在内部,如果您希望某些对象的输入更加严格.

As you can see, there is simply no payload here. That means that you need to tell TypeScript that inside the if you expect some object that is typed more stricly.

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

I would try (assuming that your Action class is named 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):

or better (assuming you use RxJS 6):

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

希望有帮助!

这篇关于在NGRX上的ActionsSubject订阅上使用操作的有效负载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆