angular - 有没有办法重构类似的角度服务?
问题描述
在这种情况下,我有这两个角度服务 userService 和 carService ,它们基本上对两个不同的对象做同样的事情(这里我从 json 文件中获取数据)。有没有办法重构这个不重复几乎相同的代码两次?
export class UserService {
constructor(private http: HttpClient) { }
getUsers(): Observable<UserDto[]> {
return this.http.get<UserDto[]>('../../assets/users.json');
}
//getUserById(){
}
}
export class CarService {
constructor(private http: HttpClient) { }
getCars(): Observable<CarDto[]> {
return this.http.get<CarDto[]>('../../assets/cars.json');
}
//getCarById(){
}
}
解决方案
如果您追求的是静态 JSON 资产,您可以简单地import
使用它们——但您可能追求的是实际的 API 请求?
在这种情况下,如果操作确实非常相似,那么通用超类可能是要走的路:
abstract class Repository<T> {
constructor(protected http: HttpClient) {}
abstract readonly basePath: string;
getAll() {
return this.http.get<T[]>(this.basePath);
}
getById(id: string) {
return this.http.get<T>(`${this.basePath}/{$id}`);
}
}
它将具体类的声明减少到最低限度:
class UserRepository extends Repository<User> {
basePath = "users";
}
class CarRepository extends Repository<Car> {
basePath = "car";
}
推荐阅读
- javascript - 更改 Blob 文件名
- c++ - 在 c/c++ 中,二进制补码整数将 +1 转换为 -1 并将 0 转换为 1 的按位运算是什么?
- python - Django TemplateSyntaxError - 'staticfiles' 不是注册的标签库
- excel - 为许多连续行自动填充文本中的连续数字
- php - 如果元素的所有值在整个数组 PHP 中都是空白,则完全删除元素
- c - 使用c语言获取数组元素的升序
- javascript - 使用复选框交换 div 内所有内容的位置
- r - 整洁的 eval vs base 或 get() vs sym() vs as.symbol()
- docker - 使用内部网络 docker 的 Traefik 404 错误
- flutter - Flutter Text Field:如何在边框内添加图标