Angular2 DI - initializing multiple different instances in the same constructor

前端 未结 3 1073
别那么骄傲
别那么骄傲 2020-12-06 02:48

I have an Angular2 DI question. Say I have a TestService and I want to use 2 different instances of this service inside the same component. If I simply add a pr

3条回答
  •  一整个雨季
    2020-12-06 03:11

    Given that there is finite amount of instances, the straightforward way may be:

    @Component({
        providers: [
            { provide: 'TestService1', useClass: TestService },
            { provide: 'TestService2', useClass: TestService }
        ]
    })
    export class TestComponent implements OnInit {
        constructor(
            @Inject('TestService1') private _testService1: TestService,
            @Inject('TestService2') private _testService2: TestService
        ) {}
        ...
    }
    

    Or OpaqueToken counterpart to avoid overriding services with the same string identifier:

    export const TestService1 = new OpaqueToken;
    export const TestService2 = new OpaqueToken;
    
    ...
    providers: [
        { provide: TestService1, useClass: TestService },
        { provide: TestService2, useClass: TestService }
    ]
    ...
    constructor(
        @Inject(TestService1) private _testService1: TestService,
        @Inject(TestService2) private _testService2: TestService
    ) {}
    

    It doesn't hurt DI in TestService constructor. And keeps the testability of TestComponent on par, both service instances can be mocked independently.

提交回复
热议问题