Return 从被拒绝的承诺中观察到

Return Observable From Promise That Gets Rejected

我正在尝试确定 how/if 我可以将 Promise 拒绝转换为类型化的 Observable。

我有一个具有类似功能的登录组件...

login() {
  const login$ = this.authenticationService.login(this.loginForm.value)
  login$
  .pipe(
    finalize(() => {
      this.loginForm.markAsPristine();
      this.isLoading = false;
    }),
    untilDestroyed(this)
  )
  .subscribe(
    (credentials) => {
      log.debug(`${credentials.username} successfully logged in`);
      this.router.navigate([this.route.snapshot.queryParams.redirect || '/'], { replaceUrl: true });
    },
    (error) => {
      log.debug(`Login error: ${error}`);
      this.error = error;
    }
  )
}

以及使用类似方法的身份验证服务...

login(context: LoginContext): Observable<Credentials> {

  var data = {} as Credentials
  
  // Call a method that returns a Promise
  this.server.authenticate(LoginContext)
  .then((result) -> {
      data.username = result.user.username
      data.token = result.accessToken
      this.credentialsService.setCredentials(data, context.remember)
      // Not sure what to do here...need to return data somehow as an Observable
      // return data
    })
  .catch((err) => {
      // Not sure what to do here either...need to bubble the err up so that it's caught in subscribe
      // return throwError(err)
    })
}

如果 Promise 解决了,我如何 return 一个 Observable<Credentials>,如果它拒绝,我如何冒出错误?

我知道如果我将身份验证服务功能更改为 return Promise<Observable<Credentials>>,我可以使一切正常,这很好,但是为了学习新事物,我正在努力弄清楚如果可以的话。

您可以使用 from function 将任何 Promise 转换为 Observable:

import { from } from 'rxjs';

// ...

class YourClass {
  login(context: LoginContext): Observable<Credentials> {
    return from(this.server.authenticate(LoginContext).then(result => {
      const credentials: Credentials = {
        username: result.user.username,
        token: result.accessToken
      }; 
      this.credentialsService.setCredentials(credentials, context.remember);
      return credentials;
    }));
  }
}