【问题标题】:Neasted RXJS Observables嵌套的 RXJS 可观察对象
【发布时间】:2020-08-28 21:21:04
【问题描述】:

我正在使用 RXJS 6.5.4

在我的打字稿服务中,我有:

isAuthenticated(): Observable<boolean> {
   // request
}
currentUserPromise(): Promise<User> {
   // request the User model and return via Promise.
}

我的第二种方法,我需要验证会话是否经过身份验证,然后请求当前用户并将其转换为另一个 Observable 以解析当前用户是否是管理员。

我正在尝试这个,但我遇到了错误:

isAdmin(): Observable<boolean> {   
   this.isAuthenticated().pipe(map(authenticated => {
      if (authenticated) {   
          return from(this.currentUserPromise().then(user => user.roles.indexOf('ADMIN') > -1)
      }
      return mapTo(false); // there is no authentication, so no current user and no admin!
   }));
}

这是编译错误:

Type 'Observable<Observable<boolean>>' is not assignable to type 'Observable<boolean>'.
   Type 'Observable<boolean>' is not assignable to type 'boolean'.ts(2322)

【问题讨论】:

    标签: typescript rxjs observable rxjs6


    【解决方案1】:

    如果你需要订阅一个内部 observable,你需要一个更高阶的操作符,比如switchMapmap 用于同步数据转换。 mapTo 是一个运算符,不能像你以前那样使用它,使用 of 将一个值变成一个可观察的值......你还需要返回它才能订阅它。

    isAdmin(): Observable<boolean> {   
       return this.isAuthenticated().pipe(switchMap(authenticated => {
          if (authenticated) {   
              return from(this.currentUserPromise().then(user => user.roles.indexOf('ADMIN') > -1))
          }
          return of(false); // there is no authentication, so no current user and no admin!
       }));
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-25
      • 1970-01-01
      • 2019-02-19
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多