简体   繁体   English

TypeScript 3.1.6 Angular 7 Rxjs6使用catchError在编辑器中显示错误,但代码正确运行

[英]TypeScript 3.1.6 Angular 7 Rxjs6 Using catchError shows error in editor but the code runs correctly

I am trying to return a custom error from a data service in the event of and error. 如果出现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);
            })
        );
}

The code above acutally runs as i expect it should, but the text editor indicates the following error: 上面的代码以我期望的方式自动运行,但是文本编辑器指示以下错误:

(TS) Type 'Observable<{} | (TS)类型“可观察<{} | Role[]>' is not assignable to type 'ObservableRole[] | Role []>'不能分配给'ObservableRole [] |类型。 CustomError>'. CustomError>。

Type '{} | 输入'{} | Role[]' is not assignable to type 'Role[] | Role []'不可分配给'Role [] |类型。 CustomError'. CustomError”。

Type '{}' is not assignable to type 'Role[] | 类型“ {}”不可分配给类型“角色[] | CustomError'. CustomError”。

Type '{}' is not assignable to type 'CustomError'. 类型“ {}”不可分配给类型“ CustomError”。

Property 'errorNumber' is missing in type '{}' 类型“ {}”中缺少属性“ errorNumber”

Can anyone tell me what I need to do to resolve the problem? 谁能告诉我解决该问题我需要做什么?

It turns out that this is not the only place in the code where I am having an issue with catchError. 事实证明,这不是代码中我遇到catchError问题的唯一地方。 I have a simple interceptor that will log http errors to the console. 我有一个简单的拦截器,它将HTTP错误记录到控制台。 (I was experimenting on how to use interceptors). (我正在尝试如何使用拦截器)。

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);
        }));
}

With this block of code I am getting a very similar set of messages. 通过这段代码,我得到了一组非常相似的消息。 Am I using catchError and throwError correctly? 我是否正确使用catchError和throwError?

My be, you need to import the throwError class? 是的,您需要导入throwError类吗? :

import {Observable, throwError} from 'rxjs';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM