Search code examples
angularobservablengrxngrx-storengrx-entity

Using payload of action on ActionsSubject subscription on NGRX


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

Solution

  • 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!