在 NGRX 上使用 ActionsSubject 订阅的动作负载
Using payload of action on ActionsSubject subscription on NGRX
我得到了旧的和坏的 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);
}
});
}
}
如果你看一下 ActionsSubject class 声明,你会注意到当你订阅它时,你应该得到 class Action
的对象,定义如下:
export interface Action {
type: string;
}
如您所见,这里根本就没有payload
。这意味着您需要告诉 TypeScript,如果您希望某个对象的类型更严格。
我会尝试(假设您的操作 class 被命名为 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);
});
希望对您有所帮助!
我得到了旧的和坏的 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);
}
});
}
}
如果你看一下 ActionsSubject class 声明,你会注意到当你订阅它时,你应该得到 class Action
的对象,定义如下:
export interface Action {
type: string;
}
如您所见,这里根本就没有payload
。这意味着您需要告诉 TypeScript,如果您希望某个对象的类型更严格。
我会尝试(假设您的操作 class 被命名为 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);
});
希望对您有所帮助!