我有一个ParentService和几个孩子。
@Injectable()
export class ParentService {
car:Car;
get Car():Car {
return this.car;
}
set Car(car:Car){
this.car = car;
}
...
}
@Injectable()
export class ChildService extends ParentService {
constructor(...){
super();
...
}
}
@Injectable()
export class AnotherChildService extends ParentService {
constructor(...){
super();
this.Car = new Car;
this.Car.Year = 2015;
...
}
}
我拥有的第二件事是服务,注入了ParentService。
@Injectable()
export class CarService{
constructor(private serviceProvider:ParentService){
this.car = this.serviceProvider.Car;
...
}
}
在每个模块中,我告诉'服务在此服务中使用哪个子服务。 这是模块示例之一:
@NgModule({
....
providers: [
{provide:ParentService, useClass:AnotherChildService},
....
]
})
export class AnotherChildModule{
...
}
问题是: 我确实看到注入的服务是正确的。 但是,ParentService初始化两次(构造函数被调用两次),这使得数据不正确。
E.g。在下面的serviceProvider.Car是未定义的,甚至汽车在AnotherChildService的构造函数中初始化
@Injectable()
export class CarService{
constructor(private serviceProvider:ParentService){
this.car = this.serviceProvider.Car;
...
}
}
我做错了吗?问题是什么?
答案 0 :(得分:0)
我找到了解决方案,我只需要使用useExisiting,而不是useClass。
{provide:ParentService, useExisting:AnotherChildService}
以下是参考:https://angular.io/guide/dependency-injection-in-action