如何解决(error:any)=> Observable <any>无法分配?

时间:2018-11-30 20:19:43

标签: javascript angular typescript error-handling rxjs6

saveExpense()方法中,当通过错误处理catchError (this.handleError<any>('Add Expense', []))时,此方法突出显示并显示错误: Argument type (error:any)=>Observable<any> is not assignable to parameter type (err:any, caught:Observable<T>)=>never。如何解决?

    saveExpense(userid, oExpense) {
        const httpOptions = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'Authorization': `${this.jwtToken}`
            })
        };
    return this.http.post(`http://localhost:5555/api/expense/${userid}`, JSON.stringify(oExpense), httpOptions).pipe(
        tap(
            (response: ServerMessage) => console.log(response)
        ),
        catchError(this.handleError('Add Expense', []))
    );
}

    private handleError<T>(operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {
            console.error(error);
            console.log(`${operation} failed: ${error.message}`);
            return of(result as T);
        };
    }

2 个答案:

答案 0 :(得分:0)

该语句意味着catchError()应该被赋予以签名(err:any, caught:Observable<T>)=>never作为参数的函数。

传递给catchError()的函数的签名(参数和返回类型)是什么?

答案 1 :(得分:0)

尝试一下:

import { Observable, throwError } from 'rxjs';

saveExpense(userid, oExpense) {
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': `${this.jwtToken}`
        })
    };
    return this.http
               .post(`http://localhost:5555/api/expense/${userid}`, JSON.stringify(oExpense), httpOptions)
               .pipe(
                   tap((response: ServerMessage) => console.log(response)),
                   catchError((err) => this.handleError(err)),
                );
}

private handleError(errorResponse): Observable<any> {
    console.log('error', errorResponse);
    return throwError(errorResponse);
}

我有一个如何使用拦截器的完整示例: https://github.com/dedd1993/ngx-admin/blob/master/src/app/%40core/http/http.interceptor.ts