Angular2 DI - initializing multiple different instances in the same constructor

前端 未结 3 1071
别那么骄傲
别那么骄傲 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:13

    You can inject a factory that returns a new instance every time you call it:

    @NgModule({
       providers: [{
          provide: 'testService', 
          useFactory: (/* TestService deps here like `http`*/) => 
            (/* params */) => new TestService(/* http */), 
          deps: [/* TestService deps here like `Http`*/ ]
        }]
    })
    
    
    @Component(...)
    export class TestComponent implements OnInit {
    
        constructor(@Inject('testService') private _testServiceFactory) { };
    
        ngOnInit() {
            console.log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", this._testServiceFactory( /* params */).toString());
            console.log("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", this._testServiceFactory().toString());
        }
    }
    

    Plunker example (check the output in the browser console when you click the button)

提交回复
热议问题