angular 4, how to pass on provider instance

后端 未结 1 468
无人共我
无人共我 2021-01-28 13:13

I have a Mqtt-Service, where i get some live data from (geometry and temperature).
Mqtt-Service:

        import { Injectable } from \'@angu         


        
相关标签:
1条回答
  • 2021-01-28 13:44

    Angular providers have single instances in injectors they were defined. Considering that singleton is unwanted here, it shouldn't be class provider (default type) that is instantiated on injection.

    If MqttdataproviderService class has no injectable dependencies, it doesn't necessarily have to be a provider. It can be defined as value provider, primarily for testability and extensibility reasons:

    { provide: MqttdataproviderService, useValue: MqttdataproviderService }
    

    If it has dependencies, they should be provided manually on instantiation:

    mqttprovider: MqttdataproviderService;
    
    constructor(
      @Inject(MqttdataproviderService) private _MqttdataproviderService: typeof MqttdataproviderService,
      formToClientService: FormToClientService
    ) {
      this.mqttprovider = new this._MqttdataproviderService(formToClientService);
    }
    

    If it is known that MqttdataproviderService class has injectable dependencies, factory provider can be used instead:

    export function mqttdataproviderServiceFactory (formToClientService: FormToClientService) 
      return () => return new MqttdataproviderService(formToClientService);
    }
    
    ...
    {
      provide: mqttdataproviderServiceFactory,
      useFactory: mqttdataproviderServiceFactory,
      deps: [FormToClientService]
     }
    ...
    

    Then factory function that is used to instantiate MqttdataproviderService can be injected:

    mqttprovider: MqttdataproviderService;
    
    constructor(@Inject(mqttdataproviderServiceFactory) public mqttdataproviderServiceFactory: () => MqttdataproviderService) {
      this.mqttprovider = mqttdataproviderServiceFactory();
    }
    

    In both cases FormToClientService will be a singleton. If this is undesirable, it should be handled in same way as MqttdataproviderService.

    0 讨论(0)
提交回复
热议问题