【问题标题】:Why map doesn't work after upgrading RxJS to v6.3为什么将 RxJS 升级到 v6.3 后 map 不起作用
【发布时间】:2018-11-10 15:00:25
【问题描述】:

我有一个类似this post 中描述的案例。

我有一个用户登录服务,它(除其他外)验证用户的令牌是否仍然有效。服务器的响应定义在一个接口中:

export interface UserVerifyResponse {
    success: boolean
}

我的目标是创建一个 observable,它会根据用户是否经过验证返回一个布尔值。此代码适用于 RxJS v6.2:

authenticate(): Observable<boolean> {
    return this.http.get<boolean>(
        this.apiUrl+'/verify_user'
    ).pipe(
        map<UserVerifyResponse, boolean>((receivedData: UserVerifyResponse) => {
            return receivedData.success;
        }),
        tap((data: boolean) => {console.log("User authenticated", data)}),
        catchError(this.handleError)
    )
}

但是,现在我已将 RxJS 更新到 v6.3,我收到此错误:

ERROR in src/app/login/user.service.ts(50,13): error TS2345: Argument of type 'OperatorFunction<UserVerifyResponse, boolean>' is not assignable to parameter of type 'OperatorFunction<boolean, boolean>'.
  Type 'UserVerifyResponse' is not assignable to type 'boolean'.

这让我很困扰,因为我使用这种将 API 响应映射到内部类或原语的方法(在其他地方,我有一个使用 http.get&lt;T&gt; 的服务),现在我想知道我是否应该强制使用 RxJS 6.2 还是有迁移到 6.3 的简单方法。我可以按照上述帖子的答案中的描述重写所有这些,但我想返回一个布尔值,我认为我的方法看起来更清晰。

有什么建议吗?

【问题讨论】:

  • 通过这个this.http.get&lt;boolean&gt;,你是说这个请求将返回一个可观察的发射booleans。但随后你使用map&lt;UserVerifyResponse, boolean&gt;,其中UserVerifyResponse 是一个对象,而不是boolean
  • 因为这是我希望请求返回的内容。使用 RxJS v6.2,我能够将从 API(UserVerifyResponse 类型)收到的响应转换为 boolean,因此最终http.get 将返回 boolean 类型的 Observable。为什么以前可以接受,现在逻辑错了?

标签: typescript type-conversion rxjs rxjs6 rxjs-pipeable-operators


【解决方案1】:

显然,他们改进了类型检查。

当你写this.http.get&lt;boolean&gt; 时,你是在说“这个get 正在返回一个布尔类型的Observable”,这不是你的意思。 get 会返回一个 UserVerifyResponse 类型的 Observable,你应该这样说:

authenticate(): Observable<boolean> {
    return this.http.get<UserVerifyResponse>(
        this.apiUrl+'/verify_user'
    ).pipe(
        map((receivedData) => {
            return receivedData.success;
        }),
        tap((data) => {console.log("User authenticated", data)}),
        catchError(this.handleError)
    )
}

管道将 Observable 从 UserVerifyResponse 更改为最终返回的 boolean

请注意,我已删除您输入的大部分内容。一般来说,您应该只在以下情况下指定类型:

  • 你必须这样做,就像 get() 本身一样,因为 TypeScript 编译器无法正确推断类型,
  • 您正在编写一个公开可用的函数,就像 authenticate() 的情况一样,因为虽然 TypeScript 可以推断类型,但稍后阅读您的代码的人可能不能。

【讨论】:

    猜你喜欢
    • 2016-07-14
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2021-09-16
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    相关资源
    最近更新 更多