在angular中将依赖项服务注入父类 [英] Inject dependency service to parent class in angular

查看:71
本文介绍了在angular中将依赖项服务注入父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有课程parentchild. child类扩展了parent.我需要将@Inject注入类service转换为parent,因为所有child都在使用它.我该怎么办?

I have class parent and child. The child class extends parent. I need to @Inject injectable class service to parent because all child's using it. How I can do it?

推荐答案

您不能将依赖项注入到父类中,因为Angular不会为您实例化它.它会创建您的子类的实例,也可以有效地初始化父类(这并不十分准确,因为类只是语法糖,但是适合于此讨论).

You can't inject a dependency into a parent class because Angular does not instantiate it for you. It creates an instance of your child class, which effectively initialises the parent class too (this isn't terribly accurate, as classes are just syntactic sugar, but it's suitable for this discussion).

一个常见的解决方案是将子类设置为可注入,然后使用super向上传递依赖项.例如:

One common solution is to just set up the child classes to be injectable and then pass the dependencies up using super. e.g.:

class Parent {
    constructor(protected someService: SomeService) { }
}

@Injectable()
class Child extends Parent {
    constructor(someService: SomeService) {
        super(someService);
    }
}

如果Parent本身实际上并不需要依赖项,那么最好在子类上使用@Injectable(),后者可以对依赖项有自己的私有引用.

If Parent doesn't actually need the dependency itself, you're better off just using @Injectable() on your child classes, which could have their own private reference to the dependency.

这篇关于在angular中将依赖项服务注入父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆