如何在Angular 8中向类注入依赖项

如何在Angular 8中向类注入依赖项,angular,typescript,class,dependency-injection,dependencies,Angular,Typescript,Class,Dependency Injection,Dependencies,我想在我的类中的静态类中使用ngx translate。我该怎么做?如何在单例类中进行依赖项注入 import { Injectable } from "@angular/core"; @Injectable() export class MyService { static instance: MyService; static getInstance() { if (MyService.instance) { return MySer

我想在我的类中的静态类中使用ngx translate。我该怎么做?如何在单例类中进行依赖项注入

import { Injectable } from "@angular/core";
@Injectable()
export class MyService {
    static instance: MyService;

    static getInstance() {
        if (MyService.instance) {
            return MyService.instance;
        }

        MyService.instance = new MyService();
        return MyService.instance;
    }

    constructor() {
        if (!MyService.instance) {
             MyService.instance = this;
        }

        return MyService.instance;
    }
}
就用吧。Angular已经介绍了您,因为Singleton是由DI容器内部管理的。实例将只创建一次,在另一个组件中注入
MyService
将等同于您的
MyService.getInstance()

您只需将服务范围中提供的
设置为
“root”


我不能这样做,因为我正在常量中使用MyService.methodname。这个方法是一个静态方法。我如何在静态方法中获取服务实例你不能使用依赖注入到常量中,这是不可能的,因为DI可能仍然没有初始化。您应该修改定义常量的位置,并将其转换为服务,等等
@Injectable({
  providedIn: 'root',
})
export class MyService {
   // ...
}