Angular 2 Inject Dependency outside Constructor

后端 未结 1 1187
误落风尘
误落风尘 2020-12-13 16:04

I am currently digging into DI in Angular 2. I\'m implementing a REST-Client using a generic subtypes for concrete Datatypes like this:

class RESTClient

        
相关标签:
1条回答
  • 2020-12-13 16:09

    This should provide a solution for this issue but also help in any case where one needs to inject a service without supplying it as a constructor parameter.

    I saw this answer in another post: Storing injector instance for use in components

    You can configure the Angular Injector in your AppModule class, and then use it in any other class (you can access AppModule's members from any class).

    In AppModule add:

    export class AppModule { 
      /**
         * Allows for retrieving singletons using `AppModule.injector.get(MyService)`
         * This is good to prevent injecting the service as constructor parameter.
         */
        static injector: Injector;
        constructor(injector: Injector) {
            AppModule.injector = injector;
        }
    }
    

    Then in your other class you can do the following (for this question replace MyService with Http):

    @Injectable()
    export class MyClass{
        private myService;
    
        constructor(){
            this.myService = AppModule.injector.get(MyService);
        }
    }
    

    This would be equivalent to using:

    constructor(private myService: MyService){}
    
    0 讨论(0)
提交回复
热议问题