在NGRX上的ActionsSubject订阅上使用操作的有效负载

时间:2018-07-27 18:14:53

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

我有老而坏的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);
      }
    });
  }
}

1 个答案:

答案 0 :(得分:3)

如果您看一下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);
});

希望有帮助!