角度NgRx效果,如何传递参数? [英] Angular NgRx effects, how to pass a parameter?

查看:17
本文介绍了角度NgRx效果,如何传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将调度中的id参数发送到大意,但在Google中找不到这种情况的任何示例。

以下是我已经拥有的代码:

组件:

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

和最后一个操作:

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

如何访问效果中组件(this.Package.id)发送的id?

推荐答案

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

  • 使用PipeableofType运算符,因为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) => {
      return this.service.getPackageCluster(action.id).pipe(
        map((packageCluster: PackageCluster) => new LoadClusterInfoSuccess(packageCluster)),
        catchError((err: Error) => of(new LoadClusterInfoError(err))),
     ); 
    }),  
  )
}

这篇关于角度NgRx效果,如何传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆