Angular 6 - 带有子类型的catchError

时间:2018-06-07 19:28:02

标签: angular typescript angular6

我正在开发一个与一些REST服务进行通信的角度6应用程序。所有REST服务'响应包含在这样的对象中:

{
   error: false,
   message: '',
   status: 200,
   value: {}
}

Value属性包含已获取的数据,可以是任何内容。

我已将此结构重复为具有此类

的打字稿
export class BaseRestResponse<T> {

  private _error: number;
  private _message: string;
  private _status: number;
  private _value: T;

  constructor();
  constructor(error: number, message: string, status: number, value: T);
  constructor(error?: number, message?: string, status?: number, value?: T) {
    this._error = error;
    this._message = message;
    this._status = status;
    this._value = value;
  }

  get error(): number {
    return this._error;
  }

  get message(): string {
    return this._message;
  }

  get status(): number {
    return this._status;
  }

  get value(): T {
    return this._value;
  }
}

我有一个包含一些共享数据的基本服务和调用处理http错误的函数,该函数传递给rxjs catchError

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { BaseRestResponse } from './base.rest.response';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

export abstract class BaseService {

  baseUrl = 'http://localhost:8080/xxx';

  constructor(protected http: HttpClient) {
    this.http = http;
  }

  /**
   * @param operation 
   * @param result 
   * @returns {(error:any)=>Observable<T>}
   */
  public handleHttpError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

        return of(result as T);
    };
  }
}

然后我有一个产品服务扩展我的基本服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { BaseService } from './base.service';
import { Product } from './product/product';
import { BaseRestResponse } from './base.rest.response'

const LOCAL_URL = '/product/find';

@Injectable({
  providedIn: 'root'
})
export class ProductService extends BaseService {

  private url: string;

  constructor(http: HttpClient) {
    super(http);
    this.url = this.baseUrl + LOCAL_URL;
  }

  getAll(): Observable<Product[]> {
    let resp = new BaseRestResponse<Product[]>(this.http.get<Product[]>(this.url).pipe(
      catchError(this.handleHttpError('getAll', BaseRestResponse<Product[]>)) // this line fails to compile
    ));
    return resp;
  }

}

但是我收到了这个错误:

src / app / product.service.ts(25,76)中的错误:错误TS1005:&#39;(&#39;预期。 src / app / product.service.ts(26,7):错误TS1005:&#39;)&#39;预期

我想要做的是拥有一个通用的handleHttpError函数,它可以根据需要返回BaseRestResponse,但我无法弄清楚如何解决这个问题

1 个答案:

答案 0 :(得分:1)

第二个参数BaseRestResponse<Product[]>出了问题。它需要是一个值而不是对象类型