[英]Angular - Defining error type to HttpClient.post()
Is it possible to set the type of the return error to HttpClient.post()
?是否可以将返回错误的类型设置为HttpClient.post()
? I want to force anyone who is going to consume this service to use the properties that were defined in his error interface我想强制任何要使用此服务的人使用在其错误界面中定义的属性
Example:例子:
// user.service.ts
sendData(data: User) {
return this.http
.post<User>(`${BASE_ENDPOINT}/user`, data, {
withCredentials: true
})
}
// user.component.ts
this.user.sendData(null)
.subscribe(
(success: User) => console.log(success),
(error: ResponseErrorUser) => console.log(error)
);
You can use Rxjs operators catchError and throwError to catch the error, map it into a custom object and throw this object.您可以使用 Rxjs 运算符catchError和throwError来捕获错误,将其映射到自定义对象中并抛出该对象。
import { catchError, throwError } from 'rxjs/operators';
...
...
// user.service.ts
sendData(data: User) {
return this.http
.post<User>(`/api/v1/not-available`, data, {
withCredentials: true
})
.pipe(
catchError(err => {
return throwError({
statusCode: err.status,
msg: err.message
});
})
);
}
// user.component.ts
this.sendData(null).subscribe(
(success: User) => console.log(success),
(error: { statusCode: number; msg: string }) => console.error(error)
);
For more information on custom error handling, I would recommend you to go through this blog .有关自定义错误处理的更多信息,我建议您阅读此博客。
Hope this helps.希望这可以帮助。 Cheers and happy coding!!!干杯和快乐的编码!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.