【问题标题】:How to inject dependency in to a class in Angular 8如何将依赖项注入Angular 8中的类
【发布时间】:2020-08-14 00:11:13
【问题描述】:

我想在我的类的静态类中使用 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 typescript class dependency-injection dependencies


    【解决方案1】:

    只需使用Singleton services。 Angular 已经涵盖了你,因为 Singleton 是由 DI 容器在内部管理的。实例只会被创建一次,在另一个组件中注入MyService就相当于你的MyService.getInstance()

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

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

    【讨论】:

    • 我不能这样做,因为我在常量中使用 MyService.methodname。并且该方法是静态方法。如何在静态方法中获取服务实例
    • 你不能在常量中使用依赖注入,这是不可能的,因为 DI 可能还没有初始化。您应该修改定义常量的位置并将其转换为服务等等
    猜你喜欢
    • 2016-04-15
    • 2020-02-13
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2011-05-06
    • 2018-01-25
    相关资源
    最近更新 更多