How to inject service into class (not component)

后端 未结 5 2169
醉梦人生
醉梦人生 2020-11-30 02:16

I want to inject a service into a class that is not a component.

For example:

Myservice

import {Injectable} from \'         


        
5条回答
  •  无人及你
    2020-11-30 02:37

    Injections only works with classes that are instantiated by Angulars dependency injection (DI).

    1. You need to
      • add @Injectable() to MyClass and
      • provide MyClass like providers: [MyClass] in a component or NgModule.

    When you then inject MyClass somewhere, a MyService instance gets passed to MyClass when it is instantiated by DI (before it is injected the first time).

    1. An alternative approach is to configure a custom injector like
    constructor(private injector:Injector) { 
      let resolvedProviders = ReflectiveInjector.resolve([MyClass]);
      let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);
    
      let myClass : MyClass = childInjector.get(MyClass);
    }
    

    This way myClass will be a MyClass instance, instantiated by Angulars DI, and myService will be injected to MyClass when instantiated.
    See also Getting dependency from Injector manually inside a directive

    1. Yet another way is to create the instance yourself:
    constructor(ms:myService)
    let myClass = new MyClass(ms);
    

提交回复
热议问题