gpt4 book ai didi

Angular NgRx 效果,如何传递参数?

转载 作者:太空狗 更新时间:2023-10-29 17:32:42 26 4
gpt4 key购买 nike

我正在尝试将 id 参数从调度发送到效果,我在谷歌中找不到这种情况的任何示例。

这是我已有的代码:

组件:

 ngOnInit(): void {
this.packageClass = `type-${this.package.packageType.toLowerCase()}`;
// I set the payload to the action
this.store.dispatch(new LoadClusterInfo({id: this.package.id}));
this.checkStatus();
}

效果(我需要访问值的地方)

@Effect()
getClusterInfo =
this.actions.ofType(resultActions.Type.LOAD_CLUSTER_INFO)
.pipe(
switchMap(() => {
let id = 'HARDCODED_ID';
return this.service.getPackageCluster(id); // Here is where i need the value
}),
map((packageCluster: PackageCluster) => new LoadClusterInfoSuccess(packageCluster)),
catchError((err: Error) => of(new LoadClusterInfoError(err))),
);

最后的 Action :

  export class LoadClusterInfo implements Action {
readonly type = Type.LOAD_CLUSTER_INFO;
constructor(readonly payload: any) {}
}

如何在效果中获取组件发送的id(this.package.id)?

最佳答案

您可以在 switchMap 运算符中访问操作的有效负载属性。一些额外的事情:

  • 使用可管道化的ofType 运算符,因为ofType 函数是removed in NgRx 7
  • 键入 ofType 运算符以执行键入的操作
  • 在服务流上使用mapcatchError,否则当发生错误时效果流将被销毁。 See the NgRx docs for more info .
@Effect()
getClusterInfo = this.actions
.pipe(
ofType<LoadClusterInfo>(resultActions.Type.LOAD_CLUSTER_INFO),
switchMap((action) => {
return this.service.getPackageCluster(action.id).pipe(
map((packageCluster: PackageCluster) => new LoadClusterInfoSuccess(packageCluster)),
catchError((err: Error) => of(new LoadClusterInfoError(err))),
);
}),
);

更新 NgRx v8 +

使用 createActioncreateEffect,会自动推断操作,因此您可以执行此操作并从类型中受益:

getClusterInfo = createEffect(() => {
return this.actions.pipe(
ofType(loadClusterInfo),
switchMap((action: any) => {
return this.service.getPackageCluster(action.id).pipe(
map((packageCluster: PackageCluster) => new LoadClusterInfoSuccess(packageCluster)),
catchError((err: Error) => of(new LoadClusterInfoError(err))),
);
}),
)
}

关于Angular NgRx 效果,如何传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54297317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com