Ima*_*tti 23 generics service typescript angular
我是typescript和angular2/4的新手,我正在构建一个具有两个基本实体的应用程序,即Car和Driver,我所做的就是用API调用列出它们.
我面临的问题是我为每个CarService和DriverService都有代码冗余,而且我可能为其他实体服务提供相同的代码.
到目前为止,实现如下:跳过其他ilustration方法:
@Injectable()
export class CarService {
private actionUrl: string;
private headers: Headers;
constructor(private _http: Http, private _configuration: Configuration) {
// Getting API URL and specify the root
this.actionUrl = _configuration.serverWithApiUrl + 'Car/';
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
// Function to get all Cars - API CALL: /
public GetAll = (): Observable<Car[]> => {
return this._http.get(this.actionUrl)
.map((response: Response) => <Car[]>response.json())
.catch(this.handleError);
}
// Function to get a Car by specific id - API CALL: /:id
public GetSingle = (id: number): Observable<Car> => {
return this._http.get(this.actionUrl + id)
.map((response: Response) => <Car>response.json())
.catch(this.handleError);
}
// Function to add a Car - API CALL: /create
public Add = (newCar: Car): Observable<Car> => {
return this._http.post(this.actionUrl + '/create', JSON.stringify(newCar), { headers: this.headers })
.catch(this.handleError);
}
// Function to update a Car - API CALL: /
public Update = (id: number, CarToUpdate: Car): Observable<Car> => {
return this._http.put(this.actionUrl + id, JSON.stringify(CarToUpdate), { headers: this.headers })
.catch(this.handleError);
}
// Function to delete a Car - API CALL: /:id
public Delete = (id: number): Observable<Response> => {
return this._http.delete(this.actionUrl + id)
.catch(this.handleError);
}
// Function to throw errors
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
Run Code Online (Sandbox Code Playgroud)
仅使用DriverService进行更改的是Car/
url的末尾以及数据类型Observable<Car[]>
和响应.
我想知道使用通用服务避免这种情况的最佳方法是什么,以及如何在Typescript中执行此操作.
n00*_*dl3 46
您可以创建一个抽象泛型类和两个继承自它的子类:
抽象类:
export abstract class AbstractRestService<T> {
constructor(protected _http: Http, protected actionUrl:string){
}
getAll():Observable<T[]> {
return this._http.get(this.actionUrl).map(resp=>resp.json() as T[]);
}
getOne(id:number):Observable<T> {
return this._http.get(`${this.actionUrl}${id}`).map(resp=>resp.json() as T);
}
}
Run Code Online (Sandbox Code Playgroud)
司机服务类
@Injectable()
export class DriverService extends AbstractRestService<Driver> {
constructor(http:Http,configuration:Configuration){
super(http,configuration.serverWithApiUrl+"Driver/");
}
}
Run Code Online (Sandbox Code Playgroud)
汽车服务类
@Injectable()
export class CarService extends AbstractRestService<Car> {
constructor(http:Http,configuration:Configuration) {
super(http,configuration.serverWithApiUrl+"Car/");
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,只有具体类被标记为@Injectable()
并且应该在模块内声明,而抽象类不应该.
更新Angular 4+
Http
在被弃用的类中HttpClient
,您可以将抽象类更改为:
export abstract class AbstractRestService<T> {
constructor(protected _http: HttpClient, protected actionUrl:string){
}
getAll():Observable<T[]> {
return this._http.get(this.actionUrl) as Observable<T[]>;
}
getOne(id:number):Observable<T> {
return this._http.get(`${this.actionUrl}${id}`) as Observable<T>;
}
}
Run Code Online (Sandbox Code Playgroud)
下面是基于Angular 7和RxJS 6构建的基本示例。
ApiResponse<T>
代表任何服务器响应。服务器必须具有相同的结构并无论发生什么情况都返回它:
export class ApiResponse<T> {
constructor() {
this.errors = [];
}
data: T;
errors: ApiError[];
getErrorsText(): string {
return this.errors.map(e => e.text).join(' ');
}
hasErrors(): boolean {
return this.errors.length > 0;
}
}
export class ApiError { code: ErrorCode; text: string; }
export enum ErrorCode {
UnknownError = 1,
OrderIsOutdated = 2,
...
}
Run Code Online (Sandbox Code Playgroud)
通用服务:
export class RestService<T> {
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json',
'Accept': 'application/json'})
};
private _apiEndPoint: string = environment.apiEndpoint;
constructor(private _url: string, private _http: HttpClient) { }
getAll(): Observable<ApiResponse<T[]>> {
return this.mapAndCatchError(
this._http.get<ApiResponse<T[]>>(this._apiEndPoint + this._url
, this.httpOptions)
);
}
get(id: number): Observable<ApiResponse<T>> {
return this.mapAndCatchError(
this._http.get<ApiResponse<T>>(`${this._apiEndPoint + this._url}/${id}`
, this.httpOptions)
);
}
add(resource: T): Observable<ApiResponse<number>> {
return this.mapAndCatchError(
this._http.post<ApiResponse<number>>(
this._apiEndPoint + this._url,
resource,
this.httpOptions)
);
}
// update and remove here...
// common method
makeRequest<TData>(method: string, url: string, data: any)
: Observable<ApiResponse<TData>> {
let finalUrl: string = this._apiEndPoint + url;
let body: any = null;
if (method.toUpperCase() == 'GET') {
finalUrl += '?' + this.objectToQueryString(data);
}
else {
body = data;
}
return this.mapAndCatchError<TData>(
this._http.request<ApiResponse<TData>>(
method.toUpperCase(),
finalUrl,
{ body: body, headers: this.httpOptions.headers })
);
}
/////// private methods
private mapAndCatchError<TData>(response: Observable<ApiResponse<TData>>)
: Observable<ApiResponse<TData>> {
return response.pipe(
map((r: ApiResponse<TData>) => {
var result = new ApiResponse<TData>();
Object.assign(result, r);
return result;
}),
catchError((err: HttpErrorResponse) => {
var result = new ApiResponse<TData>();
// if err.error is not ApiResponse<TData> e.g. connection issue
if (err.error instanceof ErrorEvent || err.error instanceof ProgressEvent) {
result.errors.push({ code: ErrorCode.UnknownError, text: 'Unknown error.' });
}
else {
Object.assign(result, err.error)
}
return of(result);
})
);
}
private objectToQueryString(obj: any): string {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
}
Run Code Online (Sandbox Code Playgroud)
那么你可以从RestService<T>
:
export class OrderService extends RestService<Order> {
constructor(http: HttpClient) { super('order', http); }
}
Run Code Online (Sandbox Code Playgroud)
并使用它:
this._orderService.getAll().subscribe(res => {
if (!res.hasErrors()) {
//deal with res.data : Order[]
}
else {
this._messageService.showError(res.getErrorsText());
}
});
// or
this._orderService.makeRequest<number>('post', 'order', order).subscribe(r => {
if (!r.hasErrors()) {
//deal with r.data: number
}
else
this._messageService.showError(r.getErrorsText());
});
Run Code Online (Sandbox Code Playgroud)
可以重新设计RestService<T>.ctor
并直接注入,RestService<Order>
而不需要声明和注入OrderService
。
看起来RxJS 6
不允许重新抛出/返回键入的错误。因此,RestService<T>
捕获所有错误并在强类型中返回它们ApiResponse<T>
。调用代码应该检查ApiResponse<T>.hasErrors()
而不是捕获错误Observable<T>