[英]TypeScript 3.1.6 Angular 7 Rxjs6 Using catchError shows error in editor but the code runs correctly
如果出现and错误,我试图从数据服务返回自定义错误。
public getRoles(): Observable<Array<Role> | CustomError> {
return this.http.get(this.urlService.getRoles)
.pipe(
map((res: any) => {
let roles = new Array<Role>();
res.Result.forEach(item => {
roles.push(new Role().fromItem(item));
});
return roles;
}
),
catchError(err => {
let customError = new CustomError();
customError.errorNumber = err.status;
customError.message = err.message;
return throwError(customError);
})
);
}
上面的代码以我期望的方式自动运行,但是文本编辑器指示以下错误:
(TS)类型“可观察<{} | Role []>'不能分配给'ObservableRole [] |类型。 CustomError>。
输入'{} | Role []'不可分配给'Role [] |类型。 CustomError”。
类型“ {}”不可分配给类型“角色[] | CustomError”。
类型“ {}”不可分配给类型“ CustomError”。
类型“ {}”中缺少属性“ errorNumber”
谁能告诉我解决该问题我需要做什么?
事实证明,这不是代码中我遇到catchError问题的唯一地方。 我有一个简单的拦截器,它将HTTP错误记录到控制台。 (我正在尝试如何使用拦截器)。
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(`ErrorInterceptor - ${req.url}`);
return next.handle(req)
.pipe(catchError(err => {
console.log(err);
return throwError(err);
}));
}
通过这段代码,我得到了一组非常相似的消息。 我是否正确使用catchError和throwError?
是的,您需要导入throwError类吗? :
import {Observable, throwError} from 'rxjs';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.