How to inject service into class (not component)

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

    If your service methods are pure functions, a clean way to solve this is to have static members in your service.

    your service

    import {Injectable} from '@angular/core';
    @Injectable()
    export class myService{
      public static dosomething(){
        //implementation => doesn't use `this`
      }
    }
    

    your class

    export class MyClass{
      test(){
         MyService.dosomething(); //no need to inject in constructor
      }
    }
    

提交回复
热议问题