首页 > 解决方案 > 编写自定义 ngrx 运算符并返回源 observable 类型

问题描述

我有一个自定义运算符,waitFor我在我的效果中使用它:

public effect$: Observable<Action> = createEffect(() => {
    return this.actions$.pipe(
      ofType(myAction),
      waitFor<ReturnType<typeof myAction>>([anotherAction]),
      ...etc
    );
  });

它基本上着眼于correlationId,直到动作数组被分派后才继续执行。但这不是重点。

正如预期的那样ofType,采用可观察的源并将其用作返回类型,但是我正在努力实现相同的效果。正如您在上面看到的,我ReturnType<typeof myAction>>在我的方法中使用了以下内容waitFor

export function waitFor<A extends Action>(actionsToWaitFor$: Array<Actions>): OperatorFunction<A, A> {

所以目前如果我waitFor这样打电话:

public effect$: Observable<Action> = createEffect(() => {
    return this.actions$.pipe(
      ofType(myAction),
      waitFor([anotherAction]),
      ...etc
    );
  });

然后它的类型被推断为Action,但我希望这是ReturnType<typeof theSourceObservable>默认的。所以我假设我的waitFor方法中需要这样的东西:

export function waitFor<A extends ReturnType<typeof sourceObservable?!>>(actionsToWaitFor$: Array<Actions>): OperatorFunction<A, A> {

waitFor看起来像这样:

export function waitFor<A extends Action>(actionsToWaitFor$: Array<Actions>): OperatorFunction<A, A> {
  return (source$) => {
    return source$.pipe(
      switchMap((action: A & { correlationId: string}) => {
        // use zip() to wait for all actions 
        // and when omitting map((action) => action)
        // so the original action is always returned
      })
    );
  };
}

ofType 源头看来,我需要使用Extract

更新

StackBlitz 示例显示在这里

标签: angulartypescriptngrxoftype

解决方案


这至少可以编译;我不知道它是否也能满足您的需求。

public effect3$: Observable<Action> = createEffect(() => {
  const a:Action[]= []

  return this.actions$.pipe(
    ofType(doSomething),
    this.someCustomOperatorReturningStaticTypes(),
    this.thisWontWork(a),
    tap(({aCustomProperty}) => {
      // The type is inferred
      console.log(aCustomProperty);
    }),
  )
});

private thisWontWork<A extends Action>(actionsToWaitFor$: Action[]): OperatorFunction<A, A> {
  return (source$) => {
    return source$.pipe(
      tap(() => {
        console.log('Should work')
      })
    )
  }
}

我无法在 StackBlitz 中运行它,有什么提示吗?

希望这可以帮助


推荐阅读