Using payload of action on ActionsSubject subscription on NGRX

萝らか妹 提交于 2021-02-08 05:08:09

问题


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

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);
      }
    });
  }
}

回答1:


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;
}

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.

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);
  }
});

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);
});

Hope that helps!



来源:https://stackoverflow.com/questions/51563431/using-payload-of-action-on-actionssubject-subscription-on-ngrx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!