我对 Angular 有点陌生,正在尝试理解高级开发人员编写的代码。如果我没有遵循标准的沟通惯例和措辞,请原谅我。
我有一个抽象类 abstractDatService
,它有一个抽象方法 getEntities()
,它的实现类是 impl1
和 impl2
实现类如下:
@Injectable()
export class impl1 extends abstractDatService{
private entities: Modal[] = [
{
id: 1,
type: "a",
name: "a1"
},
{
id: 2,
type: "a",
name: "a2"
}
];
public getEntities(): Observable<Modal[]> {
return of(this.entities);
}
}
现在,在我的模块中,我尝试将服务注入(inject)为:
providers: [
{
provide: abstractDatService,
useClass: impl1
},
{
provide: abstractDatService,
useClass: impl2
}
]
在这种情况下,当我尝试获取实体时,它们仅返回 impl2
类而不是 impl1
我希望实现返回两者。
谁能帮我解决这个问题?
编辑:
详细说明
我有一个组件,我在其中以一种方式显示数据
HEAD1
Data from impl1 // this line is a common component in which there is a ngFor on observable returned.
HEAD2
Data from impl2 // this line is a common component in which there is a ngFor on observable returned.
公共(public)组件是显示来自 impl1 的数据和来自 impl2 的数据的组件
最佳答案
根据评论
Please elaborate. what do you mean with you want them both? Do you mean you want the injected service to be a combination of both, so that getEntities returns the elements from both?
Yes I want to inject in a way that I get data for both models impl1 and impl2
你需要改变两件事。
第 1:您的提供商定义要包括 multi: true
providers: [
{
provide: AbstractionService,
useClass: Impl1Service,
multi: true,
},
{
provide: AbstractionService,
useClass: Impl2Service,
multi: true,
}
]
第二:用数组处理多重注入(inject)
constructor(@Inject(AbstractionService) impls: AbstractionService[]) {
const obs$ = impls.map(impl => impl.getEntities());
combineLatest(obs$).subscribe(console.log);
}
在 stackblitz 上检查相同的内容:https://stackblitz.com/edit/angular-ivy-pwysue?file=src/app/app.module.ts
关于javascript - Angular:如何注入(inject)抽象服务的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63723773/