defer() 不再允许可观察的 return 类型

defer() no longer allows the observable return type

今天我从 angular 6 升级到 7

与此同时,我不得不将 rxjs 从 6.1.0 升级到 6.3.3,将 typescript 从 2.7.2 升级到 3.1.1

现在这个 ngrx 效果方法抛出一个打字稿错误:

  @Effect()
  init$ = defer(() => {
    const userData = localStorage.getItem('user');
    return (userData)
      ? of(new Login(JSON.parse(userData)))
      : of(new Logout());
  });

Argument of type '() => Observable | Observable' is not assignable to parameter of type '() => void | Subscribable | Subscribable | PromiseLike | InteropObservable'.

看来我不能再使用 defer 来分派这样的 action,所以我不确定如何编写初始化效果。

我只需要等待商店初始化,所以在这个方法中我推迟执行,直到效果订阅了动作流。

有谁知道我该如何解决这个问题?

更新:

我也找到了 Stackblitz example that leverages ROOT_EFFECTS_INIT, but due to the fact that I am in a feature module, this doesn't work (discussed here)

import { ROOT_EFFECTS_INIT } from '@ngrx/effects';

@Effect()
  init$ = this.actions$
    .ofType(ROOT_EFFECTS_INIT)
    .pipe(
      map(() => {
        const userData = localStorage.getItem('user');
        return (userData)
          ? of(new Login(JSON.parse(userData)))
          : of(new Logout())
      })
    );

这是 TypeScript 的限制。您可以通过在箭头函数中显式指定 return 类型来解决此问题:

@Effect()
init$ = defer((): Observable<Action> => { // HERE
  const userData = localStorage.getItem('user');
  return (userData)
    ? of(new Login(JSON.parse(userData)))
    : of(new Logout());
});

或者,更具体地说:

@Effect()
init$ = defer((): Observable<Login | Logout> => { // HERE
  const userData = localStorage.getItem('user');
  return (userData)
    ? of(new Login(JSON.parse(userData)))
    : of(new Logout());
});

问题是没有明确的return类型,箭头函数的return类型被推断为:

Observable<Login> | Observable<Logout>

而不是:

Observable<Login | Logout>

有趣的是,虽然这确实是 TypeScript 的限制,但 this RxJS PR 将解决问题并会看到正确的类型推断。