首页 > 解决方案 > 如何将依赖项注入Angular 8中的类

问题描述

我想在我的类的静态类中使用 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;
    }
}

标签: angulartypescriptclassdependency-injectiondependencies

解决方案


只需使用单例服务。Angular 已经涵盖了你,因为 Singleton 是由 DI 容器在内部管理的。该实例只会创建一次,注入MyService另一个组件将等同于您的MyService.getInstance().

您只需providedIn将服务范围设置为"root"

@Injectable({
  providedIn: 'root',
})
export class MyService {
   // ...
}

推荐阅读