我正在尝试创建一个通用服务。我发现这篇文章:
https://medium.com/@krishna.acondy/a-generic-http-service-approach-for-angular-applications-a7bd8ff6a068
我用它来创造我的
数据服务
看起来是这样的:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { environment } from '../../../environments/environment';
import { Resource } from '../models/resource';
import { Serializer } from '../interfaces/serializer';
const API_URL = environment.apiUrl;
@Injectable()
export class DataService<T extends Resource> {
constructor(
private httpClient: HttpClient,
private endpoint: string,
private serializer: Serializer) {}
public create(item: T): Observable<T> {
return this.httpClient
.post<T>(`${API_URL}/${this.endpoint}`, this.serializer.toJson(item))
.map(data => this.serializer.fromJson(data) as T);
}
public update(item: T): Observable<T> {
return this.httpClient
.put<T>(`${API_URL}/${this.endpoint}/${item.id}`,
this.serializer.toJson(item))
.map(data => this.serializer.fromJson(data) as T);
}
read(id: number): Observable<T> {
return this.httpClient
.get(`${API_URL}/${this.endpoint}/${id}`)
.map((data: any) => this.serializer.fromJson(data) as T);
}
list(): Observable<T[]> {
return this.httpClient
.get(`${API_URL}/${this.endpoint}`)
.map((data: any) => this.convertData(data.items));
}
delete(id: number) {
return this.httpClient
.delete(`${API_URL}/${this.endpoint}/${id}`);
}
private convertData(data: any): T[] {
return data.map(item => this.serializer.fromJson(item));
}
}
我的
序列化程序
看起来像这样:
import { Resource } from "../models/resource";
export interface Serializer {
fromJson(json: any): Resource;
toJson(resource: Resource): any;
}
还有我的
资源
看起来像这样:
export class Resource {
id: number
}
如果我试图运行我的项目,我会收到一个错误,说明:
未捕获错误:无法解析数据服务的所有参数:([对象对象],[对象对象],?).
看起来它和
序列化程序
,但我不明白为什么。
我已经评论了
规格
文件,所以它不在那里使用,目前
数据服务
一直没有延长,所以我不知道为什么它在呻吟。
有人知道为什么吗?
建议创建一个新的服务来扩展
数据服务
(我已经试过了,但是在我发布这个问题之前,我删除了它,看它是否导致了这个问题。
现在我已经重新创建了它,我仍然得到同样的错误。
这是我的新课:
import { Injectable } from '@angular/core';
import { DataService } from './data.service';
import { HttpClient } from '@angular/common/http';
import { CategorySerializer } from '../models/category-serializer';
import { Category } from '../models/category';
@Injectable()
export class CategoryService extends DataService<Category> {
constructor(httpClient: HttpClient) {
super(
httpClient,
'categories',
new CategorySerializer()
);
}
}
和
类别
看起来像这样:
import { Resource } from "./resource";
export class Category extends Resource {
name: string
}
最重要的是
分类标准
看起来像这样:
import { Serializer } from "../interfaces/serializer";
import { Category } from "./category";
export class CategorySerializer implements Serializer {
fromJson(json: any): Category {
const model = new Category();
model.id = json.id;
model.name = json.name;
return model;
}
toJson(model: Category): any {
return {
id: model.id,
name: model.name
};
}
}
但我还是有同样的错误:(