我的情况与this post中描述的情况类似。
我有一个用户登录服务,该服务(除其他事项外)验证用户的令牌是否仍然有效。服务器的响应在接口中定义:
export interface UserVerifyResponse {
success: boolean
}
我的目的是创建一个可观察的对象,该对象将根据用户是否经过验证返回一个布尔值。这段代码适用于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。我可以重写上面提到的帖子的答案中描述的所有内容,但是我想返回一个布尔值,我认为我的方法看起来更清晰。
有什么建议吗?
答案 0 :(得分:0)
显然,他们改进了类型检查。
当您写this.http.get<boolean>
时,您是在说“此get返回的是boolean类型的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可以推断类型,但是稍后读取您的代码的人可能无法。