How to inject service into class (not component)

后端 未结 5 2171
醉梦人生
醉梦人生 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:42

    This is kind of (very) hacky, but I thought I'd share my solution as well. Note that this will only work with Singleton services (injected at app root, not component!), since they live as long as your application, and there's only ever one instance of them.

    First, in your service:

    @Injectable()
    export class MyService {
        static instance: MyService;
        constructor() {
            MyService.instance = this;
        }
    
        doSomething() {
            console.log("something!");
        }
    }
    

    Then in any class:

    export class MyClass {
        constructor() {
            MyService.instance.doSomething();
        }
    }
    

    This solution is good if you want to reduce code clutter and aren't using non-singleton services anyway.

提交回复
热议问题