[英]Typescript Generics and rxjs map
How can we write a generic RXJS map
function, and use it like an error handler applied to an Angular Http observable ? 我们如何编写通用的RXJS
map
函数,并像将其应用于应用于Angular Http的错误处理程序一样使用它?
I have tried : 我努力了 :
registerUser(user: CreateUserAPI) {
interface res {
session_key?: string;
result?: string;
error?: string;
}
return this.http
.post<res>(`${API_URL}/api/customer/register`, user)
.pipe(catchError(this.handleError), map(this.captureError));
}
captureError<T>(res: T): T {
if (res.error) { // <== TS ERROR : Property 'error' does not exist on type 'T'
Raven.captureMessage(res.error);
}
return res;
}
test(){
let user : any
this.registerUser(user).subscribe(res => {
res.error // no error
})
}
But TS is returning the error : Property 'error' does not exist on type 'T'
但是TS返回错误:
Property 'error' does not exist on type 'T'
My goal is to keep the typing of my observable when I subscribe to it later ( test()
method) 我的目标是在以后订阅时保持观察到的类型(
test()
方法)
You can set that your generic type extends interface with error
property: 您可以设置您的泛型类型扩展带有
error
属性的接口:
interface ErrorObj {
error: string;
}
captureError<T extends ErrorObj>(res: T): T {
if (res.error) {
Raven.captureMessage(res.error);
}
return res;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.