首页 > 解决方案 > 如何避免在多个组件中注入相同的依赖项

问题描述

我正在为我的应用程序使用 Angular 7。我在构造函数(---)的多个组件中注入相同的依赖项。我可以在超类/组件中注入一些并重用它吗?..如果有人知道最佳解决方案,请告诉我。

提前致谢

标签: angular

解决方案


If it's always the same injections, you can use an abstract component and use Injector.

export abstract class BaseComponent {

    protected myService1: MyService1;
    protected myService2: MyService2;
    protected myService3: MyService3;

    constructor(@Inject(Injector)public injector: Injector) {
        this.myService1 = injector.get(MyService1);
        this.myService2 = injector.get(MyService2);
        this.myService3 = injector.get(MyService3);
    }
}

@Inject allow you to not have constructor on childs.

And have childs:

export class MyComponent extends BaseComponent {
    constructor(public injector: Injector) {
        super(injector);
    }
    ...
}

or

export class MyComponent extends BaseComponent {
    ...
}

推荐阅读