【问题标题】:Observable<void | AuthError>' is not assignable to type 'Observable<Action>可观察<void | AuthError>' 不可分配给类型 'Observable<Action>
【发布时间】:2019-12-25 23:52:36
【问题描述】:

我不断收到以下错误:error TS2322: Type 'Observable&lt;void | AuthError&gt;' is not assignable to type 'Observable&lt;Action&gt;'. Type 'void | AuthError' is not assignable to type 'Action'. Type 'void' is not assignable to type 'Action'.

这是什么意思,我该如何解决?

  googleSignIn: Observable<Action> = this.actions.pipe(
    ofType(authActions.GOOGLE_SIGNIN),
    map((action: authActions.GoogleSignIn) => action.payload),
    switchMap(() => {
      return Observable.fromPromise(this.authService.googleSignIn());
    }),
    catchError(err => {
      return Observable.of(new authActions.AuthError({ error: err.message }));
    })
  );

authService.googleSignIn()

  googleSignIn() {
    this.logger.debug('Initialising desktop Google sign in');
    const provider = new auth.GoogleAuthProvider();
    let firstName = null;
    let lastName = null;
    return this.afAuth.auth.signInWithPopup(provider).then(async (result) => {
      if (result) {
        firstName = result.additionalUserInfo.profile['given_name'];
        lastName = result.additionalUserInfo.profile['family_name'];
        const path = `/users/${result.user.uid}/`;
        const doc = await this.firebaseService.docExists(path);
        if (!doc) {
          this.userService.processNewUser(result, firstName, lastName);
        }
        if (doc) {
          this.logger.debug(`${firstName} ${lastName} is a returning desktop user`);
        }
      }
    }).catch((error) => {
      this.simpleModalService.displayMessage('Oops', error.message);
    });
  }

【问题讨论】:

  • 这意味着你的方法应该返回一个 Observable,但它返回一个 Observable(如果没有错误),或者一个 Observable(如果有一个错误)。
  • switchMap 没有返回 Observable,而是返回了 Observable。我认为您需要在Observable.fromPromise(this.authService.googleSignIn()); 上使用pipe 并映射到一个动作。或者取决于你的应用逻辑返回一个动作。
  • 我已经为authService.googleSignIn() 添加了代码,如何将其映射到动作?
  • @methuselah Observable.fromPromise(this.authService.googleSignIn()).pipe(map(() => {//返回您的操作.....;您的代码未显示您想要的内容行动}))

标签: javascript angular typescript rxjs ngrx


【解决方案1】:

如果你使用的是 ngrx v8,你可以这样做

你遇到的问题是你必须从你的效果中返回一个动作

 getPost$ = createEffect(() =>
    this.actions$.pipe(
      ofType(PostActions.LoadPost),
      switchMap(action => {
        return this.postService
          .getPost(action.postId)
          .pipe(
            map(
              (post: IPost) => PostActions.LoadPostSuccess({ post }), // here is what you need to return
              catchError(errors => of(PostActions.LoadPostFail(errors)))
            )
          );
      })
    )
  );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-23
    • 2019-01-10
    • 1970-01-01
    • 2019-04-22
    • 2020-04-17
    • 2020-11-12
    • 2017-12-18
    • 1970-01-01
    相关资源
    最近更新 更多