【发布时间】: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<T> 的服务),现在我想知道我是否应该强制使用 RxJS 6.2 还是有迁移到 6.3 的简单方法。我可以按照上述帖子的答案中的描述重写所有这些,但我想返回一个布尔值,我认为我的方法看起来更清晰。
有什么建议吗?
【问题讨论】:
-
通过这个
this.http.get<boolean>,你是说这个请求将返回一个可观察的发射booleans。但随后你使用map<UserVerifyResponse, boolean>,其中UserVerifyResponse是一个对象,而不是boolean。 -
因为这是我希望请求返回的内容。使用 RxJS v6.2,我能够将从 API(
UserVerifyResponse类型)收到的响应转换为boolean,因此最终http.get将返回boolean类型的 Observable。为什么以前可以接受,现在逻辑错了?
标签: typescript type-conversion rxjs rxjs6 rxjs-pipeable-operators