如何使用@Inject并获取不在构造函数中的服务实例



我有一个通用类,里面使用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客户端,因为它不需要它,只在通用服务中创建它,方法如下:

@注入(HTTP_TOKEN?(HTTP:HttpService并在服务中的任何地方使用this.http。我的问题是,这是可能的和推荐的吗?如果是,我如何获得HttpService注入令牌,或者如果它不存在,我如何创建一个?

只有一个"优雅的";在Angular中注入任何东西的方法,这就是构造函数的方法。另一种方法是在运行时的任何时刻在构造函数和Injector.get(令牌(中注入Injector。

myService = this.injector.get(MyService);
constructor(private injector: Injector) {}

在你的代码中,它将是

export abstract class GenericCrudService<T> {
protected http = this.injector.get(HttpService);
constructor(protected injector: Injector, protected resourse: Resourse) {}
...
}
....
export class ExerciseService extends GenericCrudService<IExercise> {
constructor(injector: Injector) {
super(injector, Resourse.exercise);
}
}

然后在任何子代中,您只会将注入器传递给父代,并且父代可以在这个注入器的帮助下注入它想要的任何东西

更新:不再需要在不使用构造函数的情况下注入CCD_ 1来查询所有依赖关系。从Angular 14有一个暴露于的inject全局函数

class SomeComponent {
myService = inject(MyService);
...

最新更新