我正在开发一个与一些rest服务通信的angular 6应用程序。所有rest服务的响应都包装在如下对象中:
{
error: false,
message: '',
status: 200,
value: {}
}
value属性包含获取的数据,可以是任何内容。
我用这个类将这个结构重复为typescript
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:'(应为')。
src/app/product.service.ts(26,7):应为错误ts1005:“)”。
我想做的是得到一个广义handlehttperror函数,它可以根据需要返回一个baseresponse,但是我不知道如何解决这个问题