smnbbrv / ngx-grpc

Angular gRPC framework
MIT License
238 stars 34 forks source link

Define the host in the constructor of my service instead of in the AppModule #84

Closed MichaelGiger closed 2 years ago

MichaelGiger commented 2 years ago

I'm using the identical Docker image for multiple environments. I define environment-specific parameters in settings.json. Is there a way that I can define the host in the constructor of my service instead of in the AppModule?

smnbbrv commented 2 years ago

Hi @MichaelGiger

you can inject the corresponding token from the service constructor on any level of your application (app.module / module / component / custom injector) using standard dependency injection pattern.

By default, every service is automatically injected with

@Injectable({ providedIn: 'any' })

which means a new instance will be created for every lazily loaded module.

If this is not what is intended, e.g. a normal module or component, you can provide both the service client and the token, e.g.

@NgModule({
  providers: [
    { provide: GRPC_ECHO_SERVICE_CLIENT_SETTINGS, useValue: { host: 'abc' } },
    EchoServiceClient,
  ],
})
export class CustomModule {}

At this point a local copy of the service will be instantiated and it will use the provided configuration

Please have a look at https://github.com/ngx-grpc/ngx-grpc#per-service-clients-configuration

And, finally, every service client is just a ES6 class, so you can always create a service and save it in a local variable by passing the required parameters to the constructor