【发布时间】:2020-12-13 11:36:53
【问题描述】:
我有一个在其中使用 http 的通用类:
export abstract class GenericCrudService<T> {
constructor(protected http: HttpService, protected resourse: Resourse) {}
private entities: T[] = [];
entitiesChanged$: Subject<T[]> = new Subject();
getAllEntities() {
this.http.get<T>(environment.endpoint + this.resourse).subscribe((res) => {
this.entities = res;
this.entitiesChanged$.next(this.entities);
});
}
createEntity(entity: T) {
return this.http
.post(environment.endpoint + this.resourse, entity)
.subscribe((_) => {
this.entities.push(entity);
this.entitiesChanged$.next(this.entities);
});
}
deleteEntity(id: string) {
return this.http
.delete(environment.endpoint + this.resourse, id)
.subscribe((res: any) => {
this.entities = this.entities.filter((e: any) => e._id !== res.deleted);
this.entitiesChanged$.next(this.entities);
});
}
updateEntity(id: string, newEntity: T) {
return this.http
.put(environment.endpoint + this.resourse, id, newEntity)
.subscribe((res: any) => {
const updatedIndex = this.entities.findIndex(
(e: any) => e._id === res.updated
);
this.entities[updatedIndex] = newEntity;
this.entitiesChanged$.next(this.entities);
});
}
getLatestEntities() {
return this.entitiesChanged$.asObservable();
}
}
还有扩展该类的服务:
@Injectable({
providedIn: "root",
})
export class ExerciseService extends GenericCrudService<IExercise> {
constructor(http: HttpService) {
super(http, Resourse.exercise);
}
}
我认为最好不要在练习服务中注入 http 客户端,因为它不需要它,并且只通过执行以下操作在通用客户端中创建它:
@Inject(HTTP_TOKEN?) http : HttpService 并在服务的任何地方使用 this.http。我的问题是,是否有可能并被推荐,如果可以,我怎样才能获得 HttpService 注入令牌,或者如果它不存在,我该如何创建一个?
【问题讨论】:
-
JFYI:
resourse = Resourse.exercise;行是多余的,因为它已经在父级中完成。在您的版本中,“分配”逻辑只是重复了。 -
是不是弄错了
-
@Andrei 那么您对这段代码的重构有何建议?
标签: angular dependency-injection