【发布时间】:2019-03-23 14:01:13
【问题描述】:
我不确定是否应该为数据库中的每个表使用单独的服务(获取或/和删除数据)。还是可以将它们保留在一项服务中?我认为无论哪种方式都可以,我对 Angular 有点陌生,所以只是要求一个正确的答案。
db.json:
{
"products": [
{
"id": 1,
"name": "Product1",
"description": "fdfdf",
"price": 10.20
},
{
"id": 2,
"name": "Product2",
"description": "fdfdf",
"price": 20.00
},
{
"id": 3,
"name": "Product3",
"description": "fdfdf",
"price": 30.00
},
{
"id": 4,
"name": "Product4",
"description": "fdfdf",
"price": 40.00
}
],
"brands": [
{
"name": "brand1",
"country": "country1"
},
{
"name": "brand2",
"country": "country2"
},
{
"name": "brand3",
"country": "country3"
}
]
}
my service:
export class ProductService {
private url: string;
constructor(private http: HttpClient) {
this.url = 'http://localhost:3000';
}
public getJsonProducts(): Observable<any> {
return this.http.get(this.url + '/products');
}
public getJsonBrands(): Observable<any> {
return this.http.get(this.url + '/brands');
}
}
【问题讨论】:
-
最佳实践是每个资源一个服务。服务应该小而专注。通常,一种基本服务会成为许多服务的基础,例如某种 http 助手。在一个非常简单的应用程序中将所有资源保存在一个服务中可能很好,但任何远程复杂的东西都会变得混乱和难以管理。但是,这是一个意见问题,而不是特定的编程问题,不适合 SO
-
您的数据库是否只有两个表?如果是这样,那也没关系。它有100个吗?如果是这样,您是否愿意接受一个包含数百种不同方法并且每个开发人员每次需要更改或添加某些内容时都必须修改的类?
标签: angular