首页 > 解决方案 > 构建应用程序时,装饰器 NgRx/Effects 不支持函数调用

问题描述

我正在使用 Loopback SDK 生成器来生成 NgRx 存储/效果模块。我定制了库以支持所需的主要更改。

然后我编写了自定义效果来监听 GuardNotFound 动作并重定向到 404 页面,但它在构建应用程序时不起作用。

这是我的custom-effects.ts 文件

@Injectable()
export class GuardFailEffect {
  constructor(private action$: Actions, private router: Router) {
  }
  @Effect({ dispatch: false })
  redirect$ = this.action$.pipe(
    ofType('[Campaign] Guard Fail', '[LoopbackAuth] Auth Guard fail'),
    tap(() => {
      this.router.navigateByUrl('/404');
    })
  );
}

export const CustomEffects= copy(LoopbackEffects); <--- array of effects classes generated from SDK
CustomEffects.push(GuardFailEffect); <--- inserting my custom effect


//function to deep copy the array of Classes aka objects
export function copy(o) {
  let output, v, key;
  output = Array.isArray(o) ? [] : {};
  for (key in o) {
    v = o[key];
    output[key] = typeof v === 'object' && v !== null ? copy(v) : v;
  }
  return output;
}

应用模块.ts

imports : [
EffectsModule.forRoot(CustomEffects)
]

在构建应用程序时出现此错误

    ERROR in src\app\app.module.ts(89,27): Error during template compile of 'AppModule'
  Function calls are not supported in decorators but 'copy' was called in 'CustomEffects'
    'CustomEffects' calls 'copy'.

=> 如果我不深度复制数组,它会在使用推送功能时给我一个错误

[ts]
Argument of type 'typeof GuardFailEffect' is not assignable to parameter of type 'typeof LoopbackAuthEffects ... 5 more ... | typeof SubscriptionEffects'.
  Type 'typeof GuardFailEffect' is not assignable to type 'typeof SubscriptionEffects'.
    Types of parameters 'router' and 'subscription' are incompatible.
      Type 'SubscriptionApi' is not assignable to type 'Router'.
        Property 'rootComponentType' is missing in type 'SubscriptionApi'.
class GuardFailEffect

有人可以指出我正确的方向吗?

标签: javascriptangulartypescriptngrxngrx-effects

解决方案


我会forRoot在您的情况下使用该模式来构建您要导入的模块。这应该允许您运行自定义代码。

@NgModule({
})
export class CustomEffectsModule {
  static forRoot() {
    const customEffects= this.copy(LoopbackEffects);
    customEffects.push(GuardFailEffect)
    return EffectsModule.forRoot(customEffects);
  }

  private static copy(o) {
    let output = Array.isArray(o) ? [] : {};
    for (let key in o) {
      let v = o[key];
      output[key] = typeof v === 'object' && v !== null ? copy(v) : v;
    }
    return output;
  }
}

应用模块.ts

imports : [
  CustomEffectsModule.forRoot()
]

推荐阅读