在我有这两个角度服务的情况下,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(){
}
}
答案 0 :(得分:0)
使用一项具有两项功能的服务
export class UserService {
const urls = {
user: '../../assets/users.json',
car: '../../assets/cars.json'
}
constructor(private http: HttpClient) { }
getUsers(): Observable<UserDto[]> {
return this.http.get<UserDto[]>(urls.user);
}
getCars(): Observable<CarDto[]> {
return this.http.get<CarDto[]>(urls.car);
}
}
}
答案 1 :(得分:0)
也许尝试这种方法:
const uris = {
user: 'api/users',
car: 'api/cars',
};
export class CommonService {
private ULIs = uris;
constructor(private http: HttpClient) {}
getEntities(type: string): Observable<any[]> {
return this.http.get(this.ULIs[type]);
}
getEntitiyById(type: string): Observable<any> {
return this.http.get(`${this.ULIs[type]}/id`);
}
}
但是恕我直言,这不行……也许在开始应用时很有用,但是在开发的几个月中,您也会对其进行重构。
答案 2 :(得分:0)
如果您使用静态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";
}