首页 > 解决方案 > 有没有办法重构类似的角度服务?

问题描述

在这种情况下,我有这两个角度服务 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(){
    }
}

标签: angularrefactoring

解决方案


如果您追求的是静态 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";
}

推荐阅读