0

i would like to inject an existing generic service into an custom RXJS Operator, but receive every time only a new instance. And the new instance is for me useless. I could pass the service as a parameter. However, I find that ugly

What must i do, to inject an existing generic service instance?

The Service

    @Injectable({providedIn: 'root'})
    export class FormService<T> {
      public obs$: Subject<T> = new Subject<T>();

      constructor() {}
    }

the example Operator

export const DatasetUpdateOperator = <T>(propertyKey: string) => (source$) => {
const inject = Injector.create({
    providers: [{
      provide: FormService,
      useFactory: () => (new FormService<T>())
    }]
  });

  inject.get<FormService<T>>(FormService).obs$.subscribe((output) => {
    console.log(output);
  });
  return new Observable(...);
}

The Module

@NgModule({
  declarations: [...],
  exports: [...],
  providers: [
    FormService
  ],
  imports: [...]
})
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Andy C
  • 19
  • 1
  • 3
  • If you don't want a new instance, why do you explicitly useFactory with a factory that creates a new instance? – jonrsharpe Apr 18 '21 at 19:53
  • That was my last stand. I've tried a lot. But nothing led to the goal. I thought I might be able to tap the instance that way – Andy C Apr 18 '21 at 20:03
  • you can implement this https://stackoverflow.com/questions/39409328/storing-injector-instance-for-use-in-components – Chris Apr 18 '21 at 21:07
  • 1
    I think passing the service as a param is a far better approach than using an injector in the operator. It will also be easier to test – Drenai Apr 18 '21 at 21:50

0 Answers0