我应该在注入的Angular服务上使用只读方式,而不是将其公开吗? [英] Should I use readonly on injected Angular services instead of making them public?

查看:64
本文介绍了我应该在注入的Angular服务上使用只读方式,而不是将其公开吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在讨论中,一些同事说,他们像这样注入Angular服务:

I had a discussion today where some of my colleagues said that they inject their Angular services like that:

constructor(readonly language: I18nService)

他们说这样做是因为它阻止了我组件的使用者更改注入的服务,就像这样:

They said they do this because it prevents consumers of my component to change the injected service, kinda like that:

@Component({ ... })
class ComponentA {
    constructor(public language: I18nService) {}
}

@Component({ ... })
class ComponentB {
    @ViewChild(ComponentA) compA: ComponentA;
    constructor() {
        this.compA.language = new I18nService();
    }
}

因此,尽管从技术上讲它们是正确的,但我仍然不相信我应该那样做.我问自己以下问题:

So, while technically they are right I'm still not convinced that I should do it that way. I ask myself the following question:

  1. DI是Angular的基本组成部分.如果某人确实做到了,那么这个人应该更好地闯入这个坑并失败吗?或者他/她根本无法做到这一点

  1. DI is a fundamental part of Angular. If someone really does this, should this person better run into this pit and fail or should he/she not be able to do this at all

readonly 可能很难理解

  • Angular在他们的任何官方DI文档中均未使用此方法
  • 您需要了解 readonly 的工作方式,它仅保护我注入的服务的引用,但不保护任何属性
  • Angular doesn't use this approach in any of their official DI docs
  • You need to know how readonly works and that it just protects the reference of my injected service but none of the properties

在我看来,这是一个极端的问题,即使有一个简单的解决方案

In my opinion, it is a corner case problem, even though there's a simple solution to it

您怎么看?有没有我可能没有看过的官方参考书?当我尝试谷歌搜索Angular概念中 readonly 的用法时,我什么都没找到

What do you think? Are there any official references I might not have seen? I haven't found anything when I tried to google for the usage of readonly in Angular concepts

最后一个字:虽然100%正确-可以操纵对公共服务的引用:服务-我仍然不确定是否应该彻底解决这个问题,并为是否做还是不做.

One last word: While it is 100% true - It is possible to manipulate a reference of public service: Service - I'm still not sure if this should be solved at all and struggle whether to do it or not.

推荐答案

这不是您必须要做的事情,但是最好将它们设置为 readonly ,因为您可能不想要重新分配实例.

It is not something that you have to do, but it is good practice to make them readonly since you probably don't want to reassign the instance again.

只读属性可能具有初始化程序,并且可以在同一类声明中的构造函数中分配给只读属性,但否则,不允许对只读属性进行分配.

Read-only properties may have initializers and may be assigned to in constructors within the same class declaration, but otherwise, assignments to read-only properties are disallowed.

这篇关于我应该在注入的Angular服务上使用只读方式,而不是将其公开吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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